如何在不停止程序的情况下打印完整的回溯?
当您不想因错误而暂停程序时,需要使用try / except处理该错误:
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_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
比打印,记录更好:
但是,最佳实践是为模块设置一个记录器。它将知道模块的名称,并能够更改级别(在其他属性中,例如处理程序)
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
在这种情况下,您将需要该logger.exception
函数:
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_error
File "<stdin>", line 2, in raise_error
RuntimeError: 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_error
File "<stdin>", line 2, in raise_error
RuntimeError: 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_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
print(sys.exc_info()[0]
版画<class 'Exception'>
。