簡體   English   中英

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

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

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

使用time.sleep()

from time import sleep
sleep(0.05)

請注意,如果您依靠睡眠時間恰好為50 毫秒,您將不會得到那個。 它只是關於它。

使用time.sleep()

import time
time.sleep(50 / 1000)

請參閱 Python 文檔: https : //docs.python.org/library/time.html#time.sleep

有一個名為“時間”的模塊可以幫助您。 我知道兩種方法:

  1. sleep

    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

您也可以使用Timer()函數來實現。

代碼:

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)

如果第一個參數不是 None,那么它將暫停第一個參數的秒,在這個例子中:0.05 秒

如果第一個參數是 None,第二個參數是 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)
import time as t
t.sleep(0.05) 

這應該可以解決問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM