如何在Python脚本中设置时间延迟?
当前回答
虽然其他人都建议使用事实上的时间模块,但我想我应该使用matplotlib的pyplot函数pause来分享一种不同的方法。
一个例子
from matplotlib import pyplot as plt
plt.pause(5) # Pauses the program for 5 seconds
通常,这是为了防止绘图在绘制后立即消失或制作粗糙的动画。
如果您已经导入了matplotlib,这将为您保存一个导入。
其他回答
您也可以尝试以下操作:
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).
如果要在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()来停止计时器。
使用时间模块中的sleep()。对于亚秒分辨率,它可以使用浮点参数。
from time import sleep
sleep(0.1) # Time in 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)
推荐文章
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?
- 如何从生成器构建numpy数组?
- 什么时候我应该(不)想要在我的代码中使用熊猫apply() ?