如何在Python脚本中设置时间延迟?


当前回答

这将延迟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).

其他回答

我知道有五种方法: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)

Python标准库中的Tkinter库是一个可以导入的交互式工具。基本上,您可以创建按钮、框、弹出窗口和显示为窗口的东西,并使用代码进行操作。

如果使用Tkinter,请不要使用time.sleep(),因为它会破坏程序。这种情况发生在我身上。相反,使用root.after()并用毫秒来替换多少秒的值。例如,time.sleep(1)相当于Tkinter中的root.after(1000)。

否则,许多答案都指出了time.sleep(),这才是正确的方法。

这将延迟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).

使用时间模块中的sleep()。对于亚秒分辨率,它可以使用浮点参数。

from time import sleep
sleep(0.1)  # Time in seconds

用一台昏昏欲睡的发电机来找点乐子。

问题是关于时间延迟。它可以是固定的时间,但在某些情况下,我们可能需要从上次开始测量延迟。以下是一种可能的解决方案:

自上次测量的延迟(定期醒来)

情况可能是,我们希望尽可能定期地做一些事情,而不想在代码中使用所有last_time和next_time的东西。

蜂鸣器发生器

以下代码(sleep.py)定义了一个buzzergen生成器:

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)

正如我们所看到的,这个蜂鸣器并不太死板,即使我们睡过头了,也能赶上规律的睡眠时间。