如何在Python脚本中设置时间延迟?
当前回答
虽然其他人都建议使用事实上的时间模块,但我想我应该使用matplotlib的pyplot函数pause来分享一种不同的方法。
一个例子
from matplotlib import pyplot as plt
plt.pause(5) # Pauses the program for 5 seconds
通常,这是为了防止绘图在绘制后立即消失或制作粗糙的动画。
如果您已经导入了matplotlib,这将为您保存一个导入。
其他回答
如果要在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()来停止计时器。
虽然其他人都建议使用事实上的时间模块,但我想我应该使用matplotlib的pyplot函数pause来分享一种不同的方法。
一个例子
from matplotlib import pyplot as plt
plt.pause(5) # Pauses the program for 5 seconds
通常,这是为了防止绘图在绘制后立即消失或制作粗糙的动画。
如果您已经导入了matplotlib,这将为您保存一个导入。
这是一个简单的时间延迟示例:
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) # Delay for 5 seconds.
延迟的第二种方法是使用隐式等待方法:
driver.implicitly_wait(5)
当您必须等待特定操作完成或找到元素时,第三种方法更有用:
self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))
使用时间模块中的sleep()。对于亚秒分辨率,它可以使用浮点参数。
from time import sleep
sleep(0.1) # Time in seconds
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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