」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何透過超時中斷 P​​ython 函數執行?

如何透過超時中斷 P​​ython 函數執行?

發佈於2025-01-16
瀏覽:202

How to Interrupt a Python Function Execution with a Timeout?

Python 中超時中斷函數

當呼叫可能無限期停止的函數時,阻止腳本進一步執行,有必要實施逾時機制。 Python 的 signal 套件為這個問題提供了解決方案。

signal 套件主要用於 UNIX 系統,可讓您為特定函數設定逾時。如果函數超過指定的逾時,則會發出訊號以中斷執行。

範例:

考慮一個可能無限期運行的函數loop_forever()。我們需要呼叫此函數,但設定 5 秒的超時。如果函數執行時間超過 5 秒,我們想要取消它的執行。

import signal

# Register a handler for the timeout
def handler(signum, frame):
    print("Timeout! Cancelling function execution.")
    raise Exception("Timeout exceeded!")

# Register the signal function handler
signal.signal(signal.SIGALRM, handler)

# Define a timeout of 5 seconds
signal.alarm(5)

try:
    loop_forever()
except Exception as e:
    print(str(e))
    
# Cancel the timer if the function finishes before timeout
signal.alarm(0)

在此範例中,5 秒後,呼叫處理函數,引發異常。此異常在父程式碼中被捕獲,然後取消計時器並終止loop_forever()函數的執行。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3