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


当前回答

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

其他回答

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

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

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

延迟是通过时间库完成的,特别是time.sleep()函数。

让它等待一秒钟:

from time import sleep
sleep(1)

这之所以有效,是因为通过执行以下操作:

from time import sleep

你只从时间库中提取睡眠函数,这意味着你只需要调用它:

sleep(seconds)

而不是必须键入

time.sleep()

打字的时间太长了。

使用此方法,您将无法访问时间库的其他功能,也无法使用名为sleep的变量。但您可以创建一个名为time的变量。

如果您只需要模块的某些部分,那么从[library]导入[function](,[function2])非常有用。

你也可以这样做:

import time
time.sleep(1)

只要输入time,就可以访问时间库的其他功能,如time.clock()。[function](),但无法创建变量time,因为它会覆盖导入。要做的解决方案

import time as t

这将允许您将时间库引用为t,允许您执行以下操作:

t.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'))