I want to know how to put time delays in Python scripts.
#1 building
Drowsy Alternator It's a little fun.
The problem is time delay. It can be a fixed time, but in some cases, we may need to calculate the delay time since the last time. This is a possible solution:
Delay since last measurement (periodic wake-up)
It's possible that we want to do something as regularly as possible, and we don't want to disturb all last_time and next_time things in our code.
Buzzer generator
The following code (sleepy.py) defines a buzzergen generator:
import time from itertools import count def buzzergen(period): nexttime = time.time() + period for i in count(): now = time.time() tosleep = nexttime - now if tosleep > 0: time.sleep(tosleep) nexttime += period else: nexttime = now + period yield i, nexttime
Call the regular Buzzergen
from sleepy import buzzergen import time buzzer = buzzergen(3) # Planning to wake up each 3 seconds print time.time() buzzer.next() print time.time() time.sleep(2) buzzer.next() print time.time() time.sleep(5) # Sleeping a bit longer than usually buzzer.next() print time.time() buzzer.next() print time.time()
Running it, we see:
1400102636.46 1400102639.46 1400102642.46 1400102647.47 1400102650.47
We can also use it directly in the loop:
import random for ring in buzzergen(3): print "now", time.time() print "ring", ring time.sleep(random.choice([0, 2, 4, 6]))
Running it, we might see:
now 1400102751.46 ring (0, 1400102754.461676) now 1400102754.46 ring (1, 1400102757.461676) now 1400102757.46 ring (2, 1400102760.461676) now 1400102760.46 ring (3, 1400102763.461676) now 1400102766.47 ring (4, 1400102769.47115) now 1400102769.47 ring (5, 1400102772.47115) now 1400102772.47 ring (6, 1400102775.47115) now 1400102775.47 ring (7, 1400102778.47115)
As we can see, the buzzer is not too rigid, even if we overslept and exceed the regular schedule, it can make us sleepy regularly.
#2 building
In Python standard library Tkinter Library is an interactive tool that can be imported. Basically, you can create buttons, boxes, pop-up windows, and content to display as windows, and operate with code.
If you use Tkinter, do not use time.sleep(), because it can damage your program. It happened to me. Instead, use root.after() and replace the value for many seconds (in milliseconds). For example, root.after(1000) time.sleep(1) is equivalent to root.after(1000) in Tkinter.
Otherwise, many answers point to time.sleep(), which is the way to go.
#3 building
Delay is through Time library Completed, especially time.sleep() Function.
Just wait a second:
from time import sleep sleep(1)
It works by doing the following:
from time import sleep
You can only learn from Time database extract sleep function , which means you can call it with the following command:
sleep(seconds)
No input required
time.sleep()
It's hard to type.
Using this method, you will not be able to access Time library The variable named sleep is not available for other functions of. But you can create a variable called time.
If only some parts of the module are needed, you can from [library] import [function] (, [function2]) .
You can do the same:
import time time.sleep(1)
And just type time.[function] () and you can access Time library Other functions of, for example time.clock() time.[function] (), but you cannot create a variable time because it will overwrite the import. Solution
import time as t
This will allow you to Time library The reference is t, so you can do the following:
t.sleep()
This applies to any library.
#4 building
How to delay time in Python?
In a thread, I recommend using sleep function :
>>> from time import sleep >>> sleep(4)
This function actually suspends the processing of the thread in which the operating system calls it, thereby allowing other threads and processes to execute in their dormancy.
To do this, you can use it or just delay the execution of the function. For example:
>>> def party_time(): ... print('hooray!') ... >>> sleep(3); party_time() hooray!
"Long live!" After I press the Enter key for 3 seconds, it will print out.
Use the sleep example with multiple threads and processes
Likewise, sleep suspends your thread - it uses near zero processing power.
To demonstrate, create a script like this (I tried this operation in the interactive Python 3.5 shell first, but for some reasons the subprocess could not find the party ﹐ later function):
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed from time import sleep, time def party_later(kind='', n=''): sleep(3) return kind + n + ' party time!: ' + __name__ def main(): with ProcessPoolExecutor() as proc_executor: with ThreadPoolExecutor() as thread_executor: start_time = time() proc_future1 = proc_executor.submit(party_later, kind='proc', n='1') proc_future2 = proc_executor.submit(party_later, kind='proc', n='2') thread_future1 = thread_executor.submit(party_later, kind='thread', n='1') thread_future2 = thread_executor.submit(party_later, kind='thread', n='2') for f in as_completed([ proc_future1, proc_future2, thread_future1, thread_future2,]): print(f.result()) end_time = time() print('total time to execute four 3-sec functions:', end_time - start_time) if __name__ == '__main__': main()
Sample output of the script:
thread1 party time!: __main__ thread2 party time!: __main__ proc1 party time!: __mp_main__ proc2 party time!: __mp_main__ total time to execute four 3-sec functions: 3.4519670009613037
Multithreading
You can trigger the use of Timer in another thread later thread Function of object:
>>> from threading import Timer >>> t = Timer(3, party_time, args=None, kwargs=None) >>> t.start() >>> >>> hooray! >>>
A blank line indicates that the function is printed to my standard output, and I must press Enter to make sure that a prompt appears.
The advantage of this method is that I can perform other operations while the Timer thread is waiting, in which case, press Enter once before executing the function (see the first empty prompt).
stay In multiprocessing Library There is no corresponding object. You can create one, but for some reason it may not exist. For a simple timer, a child thread is more meaningful than a new child process.
#5 building
Latency can also be achieved in the following ways.
The first method:
import time time.sleep(5) # Delay for 5 seconds.
The second delay method is to use the implicit wait method:
driver.implicitly_wait(5)
The third approach is more useful when you have to wait for a specific operation to complete or an element to be found:
self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))