如何在Python脚本中设置时间延迟?
当前回答
您也可以尝试以下操作:
import time
# The time now
start = time.time()
while time.time() - start < 10: # Run 1- seconds
pass
# Do the job
现在,炮弹不会坠毁,也不会反应。
其他回答
这将延迟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).
也可以通过以下方法实现延迟。
第一种方法:
import time
time.sleep(5) # Delay for 5 seconds.
延迟的第二种方法是使用隐式等待方法:
driver.implicitly_wait(5)
当您必须等待特定操作完成或找到元素时,第三种方法更有用:
self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))
这是一个简单的时间延迟示例:
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()
虽然其他人都建议使用事实上的时间模块,但我想我应该使用matplotlib的pyplot函数pause来分享一种不同的方法。
一个例子
from matplotlib import pyplot as plt
plt.pause(5) # Pauses the program for 5 seconds
通常,这是为了防止绘图在绘制后立即消失或制作粗糙的动画。
如果您已经导入了matplotlib,这将为您保存一个导入。
我知道有五种方法: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)