如何让我的程序睡眠50毫秒?

如何让我的Python程序睡眠50毫秒?

695795 次浏览

使用time.sleep()

import time
time.sleep(50 / 1000)

查看Python留档:https://docs.python.org/library/time.html#time.sleep

使用time.sleep()

from time import sleep
sleep(0.05)

请注意,如果你依靠睡眠完全 50毫秒,你不会得到这个。它只是关于它。

你也可以使用pyautogui作为:

import pyautogui
pyautogui._autoPause(0.05, False)

如果第一个参数不是无,那么它将暂停第一个参数的秒,在本例中为:0.05秒

如果第一个参数为无,第二个参数为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)

您也可以使用Timer()函数来执行此操作。

代码:

from threading import Timer


def hello():
print("Hello")


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

有一个名为“时间”的模块可以帮助您。我知道两种方法:

  1. sleep

    睡眠(参考)要求程序等待,然后执行其余的代码。

    有两种方法可以使用睡眠:

    import time # Import whole time module
    print("0.00 seconds")
    time.sleep(0.05) # 50 milliseconds... make sure you put time. if you import time!
    print("0.05 seconds")
    

    第二种方法不导入整个模块,它只是休眠。

    from time import sleep # Just the sleep function from module time
    print("0.00 sec")
    sleep(0.05) # Don't put time. this time, as it will be confused. You did
    # not import the whole module
    print("0.05 sec")
    
  2. unix时间以来的使用时间。

    如果您需要运行循环,这种方式很有用。但这种方式稍微复杂一些。

    time_not_passed = True
    from time import time # You can import the whole module like last time. Just don't forget the time. before to signal it.
    
    
    init_time = time() # Or time.time() if whole module imported
    print("0.00 secs")
    while True: # Init loop
    if init_time + 0.05 <= time() and time_not_passed: # Time not passed variable is important as we want this to run once. !!! time.time() if whole module imported :O
    print("0.05 secs")
    time_not_passed = False