Python将异常信息转为字符串

Python将异常信息转为字符串

try:
    test()
except:
    import traceback, sys
    traceback.print_exc()  # 打印异常信息
    
    exc_type, exc_value, exc_traceback = sys.exc_info()
    error = str(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))  # 将异常信息转为字符串
    
    print(error)

erorr变量信息:

['Traceback (most recent call last):\n', '  File "D:/Projects/PycharmProjects/airflow/test.py", line 8, in \n    test()\n', '  File "D:\\Projects\\PycharmProjects\\airflow\\apps\\tasks\\celery_tasks.py", line 3, in test\n    raise Exception(\'报错了\')\n', 'Exception: 报错了\n']

你可能感兴趣的:(Python)