如何使我的Python程序休眠50毫秒?


Answers:



83

需要注意的是,如果你依靠睡眠服用正好 50毫秒,你不会得到那个。就是这样。


35
请注意,它可能比某些平台上的时间长10或15毫秒。
Kylotan

3
在给定系统上是否存在持续的延迟?
user391339 '18

7
@ user391339从经验来看,这是不一致的。线程/进程优先级,平均CPU负载,可用内存以及其他众多因素使得所有调用都不精确。系统越忙,不精确度越高。
大卫,

2
根据文档,自Python 3.5起,尽管“函数[ time.sleep(secs)] 至少处于 休眠状态”,可能会很有趣secs
埃里亚斯·斯特雷


2

也可以使用pyautogui作为

import pyautogui
pyautogui._autoPause(0.05,False)

如果first不为None,则它将暂停第一个arg秒,在此示例中:0.05秒

如果first为None,第二arg为True,则它将休眠以设置的全局暂停设置

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)

1
以某种方式,最好使用time.sleep而不是使用此方法,但是如果您希望您的程序是纯autopygui,则可以使用这种方法。
okie

2

您也可以使用Timer()功能来实现。

码:

from threading import Timer

def hello():
  print("Hello")

t = Timer(0.05, hello)
t.start()  # After 0.05 seconds, "Hello" will be printed
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.