python等待1秒 - 如何在Python中延迟时间?
python死循环sleep (9)
我想知道如何在Python脚本中加时间延迟。
如何在Python中延迟时间?
在一个线程中我建议睡眠功能:
>>> from time import sleep
>>> sleep(4)
这实际上暂停了操作系统调用它的线程的处理,允许其他线程和进程在休眠时执行。
将其用于此目的,或仅仅是为了延迟执行某个功能。 例如:
>>> def party_time():
... print('hooray!')
...
>>> sleep(3); party_time()
hooray!
“万岁!” 点击Enter后3秒打印。
使用具有多个线程和进程的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
线程对象触发稍后在单独线程中调用的函数:
>>> from threading import Timer
>>> t = Timer(3, party_time, args=None, kwargs=None)
>>> t.start()
>>>
>>> hooray!
>>>
空白行说明该功能打印到我的标准输出,我必须按Enter键以确保我出现提示。
这种方法的好处是,当Timer
线程正在等待时,我能够做其他事情,在这种情况下, 按一次Enter键 - 在函数执行之前(参见第一个空提示)。
多处理库中没有相应的对象。 你可以创建一个,但它可能不存在是有原因的。 对于简单的计时器而言,子线程比整个新的子进程更有意义。
Python标准库中的tkinter库是一个可以导入的交互式工具。 基本上,您可以创建按钮和框,弹出窗口以及显示为您使用代码操作的窗口的内容。
如果你使用TIME.SLEEP()
,请不要使用TIME.SLEEP()
因为它会TIME.SLEEP()
你的程序。 这发生在我身上。 相反,使用root.after()
并用毫秒替换多秒的值。 例如, root.after(1000)
time.sleep(1)
相当于root.after(1000)
。
否则, time.sleep()
,许多答案已经指出,这是要走的路。
可以使用三种方法实现延迟。
让我们从最简单的一个开始:
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时间的最佳方法是使用time
库。 像这样:
import time
time.sleep(10)
只需用你想要延迟的秒数替换10即可。 您可以使用'10 .1','5.07'等格式。
不建议将其与Tkinter一起使用
您可以在时间模块中使用sleep()
函数。 它可以采用浮动参数进行亚秒级分辨率。
from time import sleep
sleep(0.1) # Time in seconds.
我知道有4种方法: pygame.time.wait()
, pygame.time.wait()
,matplotlib的pyplot.pause()
和pyplot.pause()
.after()
。
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')
请阅读https://web.archive.org/web/20090207081238/http://faqts.com/knowledge_base/view.phtml/aid/2609/fid/378 ,它可以帮助您进一步:
在时间模块中尝试睡眠功能。
import time time.sleep(60)
并将其置于
while
循环中,语句只会在分钟执行...这样您就可以按预定义的时间间隔运行语句,无论命令执行的时间长短(只需不到一分钟或5或60分钟)或者你设置的任何东西)例如,我想每分钟运行一次ping。 如果我只是time.sleep(60)
或time.sleep(45)
,ping将不会总是花费相同的时间。 这是代码:)time.sleep(time.localtime(time.time())[5])
[5]
只是将时间从time.localtime()
的返回值中拉出来。关于
time.sleep
是它支持浮点数!import time time.sleep(0.1)
这是一个时间延迟的简单示例:
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()
import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.
这是另一个例子,大约每分钟运行一次:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).