簡體   English   中英

檢查python腳本是否正常運行以及是否沒有重新運行?

[英]Check if a python script is running properly and if it isn't re-run it?

我有一個腳本,確實有錯誤,並且由於錯誤而每隔幾個小時就會停止。 我不使用Python編寫代碼,但我了解基本知識,所以我想知道如何制作一個腳本來檢查另一個腳本中的錯誤,如果真的是,請重新運行它? 抱歉,沒有給出任何示例,但我想您已經明白了,並且因為我不擅長Python,所以這樣做比嘗試理解腳本並進行編輯要容易得多。 任何幫助是極大的贊賞。

到目前為止,最簡單的方法是等待它退出,並在崩潰時始終重新啟動它。 在程序運行時,以下bash循環將不執行任何操作,並在退出后立即重新啟動它:

while true
do
    python buggy_script.py arguments
    echo oops, restarting...
done

就是這樣。 它會永遠運行,直到您殺死正在運行它的bash腳本為止。

PS。 當然,這假設您使用的是OS X或Linux; 如果您使用的是Windows,請使用等效的批處理或PowerShell腳本。

您可以為腳本創建一個守護程序。

基本上將主要功能保持在一個可以永久運行的循環中。 import logging import time if __name__ == '__main__': while True: //log errors logging.basicConfig(filename='log_file.log', level=logging.DEBUG) // use try except to handle exceptions try: // your code statements and function calls except Exception as e: // log the error for debugging logging.error(str(e)) // sleep the program if you want it to for desired amount of time. time.sleep(delay)

我設置的日志記錄級別是debug。 您可以將其設置為任何其他選擇。

參考文獻:

記錄文檔-https: //docs.python.org/3/library/logging.html

處理異常-https: //docs.python.org/3/tutorial/errors.html#handling-exceptions

暫無
暫無

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

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