[英]Python Error Handling Retry Code
我試圖建立一個定義,對我的定義進行錯誤檢查。 構造此代碼以進行錯誤處理的正確方法是什么?
我希望腳本運行指定的定義,如果失敗,請重試多次,如果超時則將其終止。
import time
def open_file():
open('testfile.py')
def run_def(definition):
for i in range(0, 4):
try:
definition
str_error = None
except Exception as str_error:
pass
if str_error:
time.sleep(1)
print(str_error)
else:
break
print('kill script')
run_def(open_file())
當我嘗試將定義傳遞到錯誤檢查定義時出現錯誤。 但是,如果我不將錯誤檢查器放入單獨的定義中,則腳本可以工作。
FileNotFoundError: [Errno 2] No such file or directory: 'testfile.py'
我不確定您要做什么,但是如果您想捕獲異常,則應將調用函數放在try / except
塊中。
像這樣:
import time
def open_file():
open('testfile.py')
def run_def(definition):
for i in range(0, 4):
try:
definition()
except Exception as str_error:
if str_error:
time.sleep(1)
print(str_error)
else:
break
print('kill script')
run_def(open_file)
except
您不需要通過。
而且,您無需先初始化str_error
變量。 (除非您之前使用過...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.