我该如何让我的Python程序休眠50毫秒?
使用 time.sleep()
from time import sleep
sleep(0.05)
time.sleep(secs)
至少会休眠secs
秒。 - Elias Strehle使用time.sleep()
:
import time
time.sleep(50 / 1000)
请参阅 Python 文档:https://docs.python.org/library/time.html#time.sleep
有一个名为“time”的模块可以帮助你。我知道两种方法:
sleep
sleep
(参考)让程序等待一段时间,然后再执行其余的代码。
有两种使用 sleep
的方法:
import time # 导入整个 time 模块
print("0.00 秒")
time.sleep(0.05) # 50 毫秒……确保你导入了 time!
print("0.05 秒")
第二种方法不会导入整个模块,只是让它睡眠。
from time import sleep # 从 time 模块中仅导入 sleep 函数
print("0.00 秒")
sleep(0.05) # 这次不要加 time.,否则会混淆。你没有导入整个模块
print("0.05 秒")
使用 time.monotonic()
计算自开机以来的时间。
如果需要循环运行,这种方式非常有用。但这种方式稍微复杂一些。time.monotonic
比 time.time
更好,因为它不考虑闰秒,而是计算自开机以来的时间。(来源:Mark Lakata)
time_not_passed = True
from time import monotonic as time # 导入 time.monotonic,但为了简单起见将其命名为“time”
init_time = time() # 如果导入整个模块,则使用 time.monotonic()
print("0.00 秒")
while True: # 初始化循环
if init_time + 0.05 <= time() and time_not_passed: # 时间未过变量很重要,因为我们只想运行一次。!!! 如果导入整个模块,则使用 time.monotonic() :O
print("0.05 秒")
time_not_passed = False
time.time()
来测量经过的时间。最好使用 time.monotonic()
,它保证以均匀的速率增加。实际上有些情况下 time()
可能会因为闰秒等原因而跳变。time.monotonic()
与 Linux 纪元时间没有绝对的关联,但通常在系统启动时从 0 开始计数。 - Mark LakataTimer()
函数来实现。from threading import Timer
def hello():
print("Hello")
t = Timer(0.05, hello)
t.start() # After 0.05 seconds, "Hello" will be printed
你也可以将pyautogui用作:
import pyautogui
pyautogui._autoPause(0.05, False)
pyautogui.PAUSE = int
def _autoPause(pause, _pause):
"""If `pause` is not `None`, then sleep for `pause` seconds.
If `_pause` is `True`, then sleep for `PAUSE` seconds (the global pause setting).
This function is called at the end of all of PyAutoGUI's mouse and keyboard functions. Normally, `_pause`
is set to `True` to add a short sleep so that the user can engage the failsafe. By default, this sleep
is as long as `PAUSE` settings. However, this can be override by setting `pause`, in which case the sleep
is as long as `pause` seconds.
"""
if pause is not None:
time.sleep(pause)
elif _pause:
assert isinstance(PAUSE, int) or isinstance(PAUSE, float)
time.sleep(PAUSE)
time.sleep
,而不是这种方法,但如果你想让你的程序纯粹使用autopygui,那么这也是一种方式。 - okie