for i in something:for j in somethingelse:for k in whatever:try:something_complex(i, j, k)except Exception, e:print etry:something_less_complex(i, j)except Exception, e:print e
try:do_something_that_might_error()except Exception as error:handle_the_error(error)
要提取完整的回溯,我们将使用标准库中的traceback模块:
import traceback
并创建一个体面复杂的堆栈跟踪来证明我们得到了完整的堆栈跟踪:
def raise_error():raise RuntimeError('something bad happened!')
def do_something_that_might_error():raise_error()
印刷
要打印完整的回溯,请使用traceback.print_exc方法:
try:do_something_that_might_error()except Exception as error:traceback.print_exc()
哪些打印:
Traceback (most recent call last):File "<stdin>", line 2, in <module>File "<stdin>", line 2, in do_something_that_might_errorFile "<stdin>", line 2, in raise_errorRuntimeError: something bad happened!
try:do_something_that_might_error()except Exception as error:logger.exception(error)
哪些日志:
ERROR:__main__:something bad happened!Traceback (most recent call last):File "<stdin>", line 2, in <module>File "<stdin>", line 2, in do_something_that_might_errorFile "<stdin>", line 2, in raise_errorRuntimeError: something bad happened!
或者你只是想要字符串,在这种情况下,你会想要traceback.format_exc函数:
try:do_something_that_might_error()except Exception as error:logger.debug(traceback.format_exc())
哪些日志:
DEBUG:__main__:Traceback (most recent call last):File "<stdin>", line 2, in <module>File "<stdin>", line 2, in do_something_that_might_errorFile "<stdin>", line 2, in raise_errorRuntimeError: something bad happened!
结论
对于所有三个选项,我们看到我们得到了与错误时相同的输出:
>>> do_something_that_might_error()Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 2, in do_something_that_might_errorFile "<stdin>", line 2, in raise_errorRuntimeError: something bad happened!
Handled at stack lvl 0File "exc.py", line 17, in <module>stack_lvl_1()File "exc.py", line 13, in stack_lvl_1stack_lvl_2()File "exc.py", line 9, in stack_lvl_2stack_lvl_3()File "exc.py", line 5, in stack_lvl_3raise Exception('a1', 'b2', 'c3')
import traceback
def get_traceback(e):lines = traceback.format_exception(type(e), e, e.__traceback__)return ''.join(lines)
try:1/0except Exception as e:print('------Start--------')print(get_traceback(e))print('------End--------')
try:spam(1,2)except Exception as e:print('------Start--------')print(get_traceback(e))print('------End--------')
输出将是这样的:
bash-3.2$ python3 /Users/soumyabratakole/PycharmProjects/pythonProject/main.py------Start--------Traceback (most recent call last):File "/Users/soumyabratakole/PycharmProjects/pythonProject/main.py", line 26, in <module>1/0ZeroDivisionError: division by zero
------End--------------Start--------Traceback (most recent call last):File "/Users/soumyabratakole/PycharmProjects/pythonProject/main.py", line 33, in <module>spam(1,2)NameError: name 'spam' is not defined
------End--------