簡體   English   中英

在Python中的while true循環中使用計時器

[英]Using a timer in a while true loop in Python

我在Python中管理無限while循環時遇到問題,在該循環中我將插入計時器作為一種“看門狗”。 我試圖更好地解釋一下:腳本必須偵聽串行通道,並等待來自通道另一側連接的傳感器的消息。 我使用一會兒True循環來執行此操作,因為腳本必須捕獲所有正在傳遞的信號。 但是,即使可能不必要,我也想插入一個始終在每個循環中重置的計時器。 因此,如果(例如)由於某種原因導致循環卡住,計時器將結束並退出程序。 我以為我可以這樣:

def periodicUpdate():
    exitTimer = threading.Timer(60.0, sys.exit())
    while True:
        exitTimer.start()
        readData()
        exitTimer.cancel()

現在的問題是,當我啟動腳本時,它會立即退出。 似乎它在所有其余部分之前都讀取sys.exit() ,並且它不遵守計時器的構造,而只是在調用sys.exit()時它退出了。 為什么會這樣? 我嘗試更改語法,將sys.exit放在另一個函數中並調用該函數,我嘗試了其他解決方案,但始終以兩種方式運行:退出或由於不存在計時器而運行。 有人能幫我嗎? 非常感謝

似乎它在所有其余部分之前都讀取sys.exit()

當然可以。 threadint.Timer的第二個參數是將被調用的函數 您要做的是實際上調用 sys.exit並將其返回值(順便說一句,因為該調用終止了程序,因此未定義)作為要調用的函數。 這是一個錯誤,因為sys.exit的返回值不是函數,但這無關緊要,因為無論如何該程序都將終止。

你想做的是

exitTimer = threading.Timer(60.0, sys.exit) # note: no brackets

但實際上行不通的,因為sys.exit的線程將終止只是線程 總之,你不能用一個看門狗終止卡住while -loop如果這個循環是在你的主線程。 在您的特定情況下,您應該研究用於讀取數據的功能,很可能它可以讓您設置讀取超時。

刪除括號。 如果使用sys.exit() ,它將立即啟動。 當您使用sys.exit ,它將把函數作為Timer的第二個參數傳遞。

我認為您的方法不是最好的方法,而不是運行退出應用程序的計時器,為什么不簡單地使讀取數據的函數超時:

函數調用超時

在我看來,這里提出的解決方案都沒有真正起作用。 這是一個代碼示例。 很高興知道如何解決它。 另外,請在回答之前嘗試一下。

import time, threading, sys

def _exit():
    print 'exiting'
    sys.exit()

def periodicUpdate():
    exitTimer = threading.Timer(2.0, _exit)
    while True:
        exitTimer.start()
        print 'go'
        time.sleep(5)
        exitTimer.cancel()


periodicUpdate()

實際輸出為:

$python test.py
go
exiting
RuntimeError: threads can only be started once
exitTimer = threading.Timer(60.0, sys.exit)

在計時器調用中從sys.exit中刪除()

def _exit()
    sys.exit()

def periodicUpdate():
    exitTimer = threading.Timer(60.0, _exit)
    while True:
        exitTimer.start()
        readData()
        exitTimer.cancel()

在您輸入()時,解釋器將調用此函數,否則解釋器將獲得此函數的引用。

玩得開心 :)

編輯:使用_exit

threading.Timer(60.0, os._exit, [0])
def periodicUpdate():
    exitTimer = sys.exit(60.0, sys.exit())
    while sys.exit():
        sys.exit()
        readData()
        sys.exit()

if __name__ == "__main__":
    sys.exit()

不要忘記導入sys。

暫無
暫無

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

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