一、說明
1、python進程池進行多進程運行時,如果有錯誤,該進程會直接跳過,並且不會打印錯誤信息。
2、如果需要了解到進程內的錯誤信息,此時就需要通過捕獲異常來輸出錯誤信息了。
二、具體方法如下:
法一:
注:此方法不會打印錯誤代碼具體位置
a = [1, 2, 3] try: b = a[5] except Exception as ee: print(ee) s = ee # 如果想在except語句外使用ee,需要用變量儲存 # 輸出ee: # list index out of range # s: IndexError('list index out of range') ,s本身是包含錯誤類型的,所以,如果需要將錯誤信息寫入文件的話,需要通過str(s)將信息轉換為字符串(或者使用pickle.dumps(s),但不能使用json.dumps,會報錯) print(type(s)) # 輸出: # IndexError print(s) # 輸出: # list index out of range
法二:
注:此方法可以輸出錯誤代碼位置
import sys import traceback a = [1, 2, 3] try: b = a[5] except: error_type, error_value, error_trace = sys.exc_info() # 輸出的值是元組,分別是:錯誤類型,錯誤內容,traceback對象 print(error_type) # 與法一中的type(s)一樣 # 輸出: # IndexError print(error_value) # 與法一中的s一樣,IndexError('list index out of range') # 輸出: # IndexError('list index out of range') # 對於error_trace對象,需要通過trackback模塊來提取具體內容 # 法1(此方法只顯示錯誤代碼的行數): for info in traceback.extract_tb(error_trace): print(info) # 輸出: # <FrameSummary file <ipython-input-85-e62dacac329b>, line 6 in <module>> # 法2(此方法會顯示錯誤代碼的內容): with open('error.txt', 'a') as f: traceback.print_tb(error_trace) traceback.print_tb(error_trace, file=f) # 將輸出信息存入文件 # 輸出: # File "<ipython-input-85-e62dacac329b>", line 6, in <module> # b = a[5]