我想知道如何在Python脚本中设置一个时间延迟。
你可以使用time
模块中的sleep()
函数。它可以接受一个浮动参数以获得亚秒级分辨率。
from time import sleep
sleep(0.1) # Time in seconds
如何在Python中做一个时间延迟?
在单线程中我建议使用【睡眠函数】1。
>>> from time import sleep
>>> sleep(4)
这个函数实际上是暂停了操作系统调用它的线程的处理,允许其他线程和进程在它睡眠时执行。
使用它的目的,或者仅仅是为了延迟一个函数的执行。 例如:{{5519509}}。
>>> def party_time():
... print('hooray!')
...
>>> sleep(3); party_time()
hooray!
"万岁!"。 在我按下Enter3秒后被打印出来。
sleep
与多线程和进程的例子。同样,sleep
会暂停你的线程--它的处理能力几乎为零。
为了演示,请创建一个这样的脚本 (我第一次在交互式的 Python 3.5 shell 中尝试这样做,但由于某些原因,子进程无法找到 party_later
函数)。
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()
此脚本的输出示例。
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
您可以使用Timer
[threading][3]对象触发一个函数在稍后的时间被单独的线程调用。
>>> from threading import Timer
>>> t = Timer(3, party_time, args=None, kwargs=None)
>>> t.start()
>>>
>>> hooray!
>>>
空行说明该函数打印到了我的标准输出,我不得不按下Enter</kbd>。 以确保我是在提示。
这种方法的好处是,当Timer
线程在等待时,我能够做其他事情,在这种情况下,点击Enter</kbd>。
一次--在函数执行之前(见第一个空提示)。
在[多处理库][2]中没有一个各自的对象。 你可以创建一个,但它可能不存在是有原因的。 对于一个简单的定时器来说,一个子线程比一个全新的子进程更有意义。
1:
[2]: https://docs.python.org/3/library/multiprocessing.html [3]: https://docs.python.org/3/library/threading.html
昏昏欲睡的发电机的一点乐趣。
这个问题是关于时间延迟的。它可以是固定的时间,但在某些情况下,我们可能需要一个从上次开始测量的延迟。这里有一个可能的解决方案。
情况可能是,我们想尽可能有规律地做一些事情,而且我们不想在代码中到处都是 "last_time"、"next_time "的东西。
下面的代码(sleepy.py)定义了一个`蜂鸣器'发生器。
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
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()
并运行它,我们看到。
1400102636.46
1400102639.46
1400102642.46
1400102647.47
1400102650.47
我们也可以在一个循环中直接使用它。
import random
for ring in buzzergen(3):
print "now", time.time()
print "ring", ring
time.sleep(random.choice([0, 2, 4, 6]))
而运行它,我们可能会看到。
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)
正如我们所看到的,这个蜂鸣器不是太死板,即使我们睡过头了,脱离了正常的时间表,也能让我们赶上正常的睡眠间隔。
延迟也可以通过以下方法来实现。
第一种方法
import time
time.sleep(5) # Delay for 5 seconds.
第二种延迟方法是使用隐式等待法。
driver.implicitly_wait(5)
第三种方法在需要等待某个动作完成或找到某个元素时比较有用。
self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))
Python标准库中的tkinter库是一个你可以导入的交互式工具。 基本上,你可以创建按钮、框和弹出窗口之类的东西,你可以用代码来操作。
如果你使用 tkinter,请不要使用TIME.SLEEP()
,因为它会把你的程序搞乱。
我就遇到过这种情况。
取而代之的是使用root.after()
,然后用毫秒代替多少秒的值。
例如,time.sleep(1)
相当于tkinter中的root.after(1000)
。
否则,time.sleep()
,很多答案都指出了,这才是正确的方法。
我知道的方法有5种。
time.sleep()
、pygame.time.wait()
、matplotlib的pyplot.pause()
、.after()
、driver.implicitly_wait()
。
time.sleep()
例子(如果使用Tkinter,请不要使用)。
import time
print('Hello')
time.sleep(5) #number of seconds
print('Bye')
pygame.time.wait()
例子(如果你不使用pygame窗口,不建议使用,但你可以立即退出窗口)。
import pygame
#If you are going to use the time module
#don't do "from pygame import *"
pygame.init()
print('Hello')
pygame.time.wait(5000)#milliseconds
print('Bye')
matplotlib'的函数pyplot.pause()
的例子(如果你不使用图形,不建议使用,但你可以立即退出图形)。
import matplotlib
print('Hello')
matplotlib.pyplot.pause(5)#seconds
print('Bye')
.after()
方法(最好用Tkinter)。
import tkinter as tk #Tkinter for python 2
root = tk.Tk()
print('Hello')
def ohhi():
print('Oh, hi!')
root.after(5000, ohhi)#milliseconds and then a function
print('Bye')
最后是driver.implicitly_wait()
方法(selenium)。
driver.implicitly_wait(5)#waits 5 seconds
延迟是通过[时间库][1],特别是[time.sleep()
][2]函数来完成的。
要只是让它等待一秒钟。
from time import sleep
sleep(1)
之所以能成功,是因为通过实践。
from time import sleep
您从 [时间库][1] 中提取 [sleep 函数][2] 仅,这意味着您可以直接用以下方式调用它。
sleep(seconds)
而不是要打出
time.sleep()
这在打字的时候很尴尬的长。
有了这个方法,你就不能使用[时间库][1]的其他功能,你也不能有一个叫sleep
的变量。
但你可以创建一个名为time
的变量。
如果你只是想要一个模块的某些部分,那么做[from [library] import [function] (, [function2])
][4]是很好的。
你同样可以这样做。
import time
time.sleep(1)
而你将可以访问[时间库][1]的其他功能,比如[time.clock()
][3],只要你输入time.[function]()
,但你不能创建变量time,因为它会覆盖导入。
解决这个问题的方法是
import time as t
这将允许您将[时间库][1]引用为t
,使您能够做到。
t.sleep()
这对任何图书馆都有效。
[1]: https://docs.python.org/2/library/time.html [2]: https://docs.python.org/2/library/time.html#time.sleep [3]: https://docs.python.org/2/library/time.html#time.clock [4]: https://docs.python.org/2/tutorial/modules.html#more-on-modules
注意在最近的python版本中(python 3.4或更高),你可以使用asyncio.sleep
。
它与异步编程和asyncio有关。
请看下面的例子。
import asyncio
from datetime import datetime
@asyncio.coroutine
def countdown(iteration_name, countdown_sec):
"""
Just count for some countdown_sec seconds and do nothing else
"""
while countdown_sec > 0:
print(f'{iteration_name} iterates: {countdown_sec} seconds')
yield from asyncio.sleep(1)
countdown_sec -= 1
loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(countdown('First Count', 2)),
asyncio.ensure_future(countdown('Second Count', 3))]
start_time = datetime.utcnow()
# run both methods. How much time will both run...?
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
print(f'total running time: {datetime.utcnow() - start_time}')
我们可能认为它会"sleep"。 第一条方法睡2秒,第二条方法睡3秒,这段代码总共运行5秒。 但它会打印出来。
total_running_time: 0:00:03.01286
推荐阅读[asyncio官方文档][1]了解更多详情
使用 time.sleep
或 Event().wait
像这样。
from threading import Event
from time import sleep
delay_in_sec = 2
# use time.sleep like this
sleep(delay_in_sec) # returns None
print(f'slept for {delay_in_sec} seconds')
# or use Event().wait like this
Event().wait(delay_in_sec) # returns False
print(f'waited for {delay_in_sec} seconds')
使用threading.Timer
,像这样。
from threading import Timer
delay_in_sec = 2
def hello(delay_in_sec):
print(f'function called after {delay_in_sec} seconds')
t = Timer(delay_in_sec, hello, [delay_in_sec]) # hello function will be called 2 sec later with [delay_in_sec] as *args parameter
t.start() # returns None
print("Started")
产出:{{{5519528}}
Started
function called after 2 seconds
timer_obj.cancel()
来停止它。这就是一个简单的时间延迟的例子。
import time
def delay(period='5'):
# If the user enters nothing, It'll wait 5 seconds
try:
#If the user not enters a int, I'll just return ''
time.sleep(period)
except:
return ''
另一个,在Tkinter。
import tkinter
def tick():
pass
root=Tk()
delay=100 # time in milliseconds
root.after(delay,tick)
root.mainloop()