And abnormal fight is already a programmer commonplace. Many times we need to print out all exception information. The more common method is the direct use of an exception to capture:
import time
def error_func():
raise ValueError("错误出现")
if __name__ == '__main__':
try:
error_func()
except ValueError as e:
print(e)
time.sleep(1)
print('继续执行')
Print results are as follows:
错误出现
继续执行
However, the above code just print the abnormality information, and no abnormal type of printing. If we project in exception handling many things you need along with 异常出现的位置
, 异常信息
, 异常的类型
they are printed out and help us troubleshoot the error.
Use traceback module format_exc way to print a complete anomaly
Sample code is as follows:
import time
def error_func():
raise ValueError("错误出现")
if __name__ == '__main__':
try:
error_func()
except ValueError:
import traceback
print(traceback.format_exc())
time.sleep(1)
print('继续执行')
The results are as follows:
Traceback (most recent call last):
File "D:/auto/pro/error_test.py", line 9, in <module>
error_func()
File "D:/auto/pro/error_test.py", line 4, in error_func
raise ValueError("错误出现")
ValueError: 错误出现
继续执行
In this way, we can complete the exceptions are printed, can help us to analyze the error.
print_exc method error messages written to the log
traceback module There are two ways to print an exception, one is format_exc
, the other is print_exc
both to do that: print_exc
the method can not only print the error message in the console, but also to write error information to a file.
The above code to improve it:
import os
import time
def error_func():
raise ValueError("错误出现")
if __name__ == '__main__':
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ERROR_LOG_PATH = os.path.join(BASE_DIR,'core','error_log.log')
try:
error_func()
except ValueError:
import traceback
traceback.print_exc(file=open(ERROR_LOG_PATH,'a+'))
time.sleep(1)
print('继续执行')
We have additional ways whereabouts in writing the error log, so help us troubleshoot the error.
参考博客:https://www.cnblogs.com/alummox/p/7465197.html