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

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

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

How do I get my Python program to sleep for 50 milliseconds?


回答 0

from time import sleep
sleep(0.05)

参考

from time import sleep
sleep(0.05)

Reference


回答 1

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

Note that if you rely on sleep taking exactly 50 ms, you won’t get that. It will just be about it.


回答 2

import time
time.sleep(50 / 1000)
import time
time.sleep(50 / 1000)

回答 3

也可以使用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)

can also using pyautogui as

import pyautogui
pyautogui._autoPause(0.05,False)

if first is not None, then it will pause for first arg second, in this example:0.05 sec

if first is None, and second arg is True, then it will sleep for global pause setting which is set with

pyautogui.PAUSE = int

if you are wondering the reason, see the source code:

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)

回答 4

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

码:

from threading import Timer

def hello():
  print("Hello")

t = Timer(0.05, hello)
t.start()  # After 0.05 seconds, "Hello" will be printed

You can also do it by using Timer() function.

Code:

from threading import Timer

def hello():
  print("Hello")

t = Timer(0.05, hello)
t.start()  # After 0.05 seconds, "Hello" will be printed