如何在Python脚本中设置时间延迟?
当前回答
如果要在Python脚本中设置时间延迟:
使用time.sleep或Event()。像这样等待:
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')
但是,如果要延迟函数的执行,请执行以下操作:
使用线程。计时器如下:
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 seconds later with [delay_in_sec] as the *args parameter
t.start() # Returns None
print("Started")
输出:
Started
function called after 2 seconds
为什么使用后一种方法?
它不会停止整个脚本的执行(传递给它的函数除外)。启动计时器后,还可以通过执行timer_obj.cancel()来停止计时器。
其他回答
这将延迟2.5秒:
import time
time.sleep(2.5)
下面是另一个例子,其中某个东西大约每分钟运行一次:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
Python标准库中的Tkinter库是一个可以导入的交互式工具。基本上,您可以创建按钮、框、弹出窗口和显示为窗口的东西,并使用代码进行操作。
如果使用Tkinter,请不要使用time.sleep(),因为它会破坏程序。这种情况发生在我身上。相反,使用root.after()并用毫秒来替换多少秒的值。例如,time.sleep(1)相当于Tkinter中的root.after(1000)。
否则,许多答案都指出了time.sleep(),这才是正确的方法。
异步休眠
请注意,在最近的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}')
我们可能认为,第一种方法会“休眠”2秒,第二种方法会休眠3秒,这段代码总共运行5秒。但它将打印:
total_running_time: 0:00:03.01286
建议阅读asyncio官方文档以了解更多详细信息。
如何在Python中设置时间延迟?
在一个线程中,我建议使用睡眠功能:
>>> from time import sleep
>>> sleep(4)
该函数实际上暂停了操作系统调用它的线程的处理,允许其他线程和进程在休眠时执行。
为此目的使用它,或者简单地延迟函数的执行。例如:
>>> def party_time():
... print('hooray!')
...
>>> sleep(3); party_time()
hooray!
“万岁!”在我按下Enter键3秒后打印。
对多个线程和进程使用睡眠的示例
同样,睡眠会暂停线程-它使用几乎为零的处理能力。
为了演示,创建一个这样的脚本(我第一次在交互式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键(见第一个空提示)。
多处理库中没有相应的对象。你可以创建一个,但它可能是没有原因的。对于一个简单的计时器来说,子线程比一个全新的子进程更有意义。
我知道有五种方法:time.sleep()、pygame.time.wait()、matplotlib的pyplot.pause()、.after()和asyncio.sleep)。
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')
最后,asyncio.sleep()方法(必须在异步循环中):
await asyncio.sleep(5)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if