如何打印完整的追溯而不停止程序? [英] How to print the full traceback without halting the program?
问题描述
try:
do_stuff()
除了:
pass
但现在我想记录错误:
try:
do_stuff()
除了异常,err:
print异常,err
请注意,这是打印到日志文件供以后审查。这通常打印非常无用的数据。我想要的是打印完全相同的行,当错误触发时没有try-except拦截异常,但我不希望它停止我的程序,因为它嵌套在一系列的for循环中,我想看到完成。
其他答案已经指出了 traceback 模块。
请注意,使用 print_exc
在某些情况下,您将无法获得您期望的内容。在Python 2.x中:
import traceback
try:
raise TypeError(
除了异常,错误:
try:
raise TypeError(Again!?!)
除了:
pass
traceback.print_exc()
...将显示最后 exception:
追溯(最近的最后一次呼叫):
文件 e.py,第7行,位于< module>
raise TypeError(Again!?!)
TypeError:再次!
如果您真的需要访问原始的 traceback strong>一个解决方案是缓存从 <$返回的异常信息 c $ c> exc_info ,并使用 print_exception
:
import traceback
import sys
try:
raise TypeError(Oups!)
除了异常,err:
try:
exc_info = sys.exc_info
#你有用的东西在这里
#(可能提高一个例外)
try:
raise TypeError(Again!?!)
除了:
通过
#有用的东西
最后:
#显示*原始*异常
traceback.print_exception(* exc_info)
del exc_info
生产:
追溯(最近的最后一次呼叫):
文件t.py,第6行在< module>
raise TypeError(Oups!)
TypeError:Oups!
尽管如此,很少有陷阱:
-
从
sys_info
:
将追溯返回值分配给处理异常的函数中的局部变量将导致循环引用。这样可以防止同一个函数中的局部变量引用的任何内容,或者通过回溯进行垃圾回收。 [...] 如果您需要追溯,请确保在使用后删除它(最好用try ... finally语句)
-
但是,从同一个文档:
从Python 2.2开始,这样的循环自动回收,当垃圾收集被启用并且它们变得不可达时,但是避免创建循环仍然更有效。
另一方面,通过允许您访问与关联的追溯异常, Python 3产生一个不那么令人惊讶的结果:
import traceback
try:
raise TypeError (Oups!)
除了异常作为错误:
try:
raise TypeError(Again!?!)
除了:
pass
traceback.print_tb(err .__ traceback__)
...将显示:
文件e3.py,第4行在< module>
raise TypeError(Oups!)
I'm writing a program that parses 10 websites, locates data files, saves the files, and then parses them to make data that can be readily used in the NumPy library. There are tons of errors this file encounters through bad links, poorly formed XML, missing entries, and other things I've yet to categorize. I initially made this program to handle errors like this:
try:
do_stuff()
except:
pass
But now I want to log errors:
try:
do_stuff()
except Exception, err:
print Exception, err
Note this is printing to a log file for later review. This usually prints very useless data. What I want is to print the exact same lines printed when the error triggers without the try-except intercepting the exception, but I don't want it to halt my program since it is nested in a series of for loops that I would like to see to completion.
Some other answer have already pointed out the traceback module.
Please notice that with print_exc
, in some corner cases, you will not obtain what you would expect. In Python 2.x:
import traceback
try:
raise TypeError("Oups!")
except Exception, err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_exc()
...will display the traceback of the last exception:
Traceback (most recent call last):
File "e.py", line 7, in <module>
raise TypeError("Again !?!")
TypeError: Again !?!
If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info
in a local variable and display it using print_exception
:
import traceback
import sys
try:
raise TypeError("Oups!")
except Exception, err:
try:
exc_info = sys.exc_info()
# do you usefull stuff here
# (potentially raising an exception)
try:
raise TypeError("Again !?!")
except:
pass
# end of useful stuff
finally:
# Display the *original* exception
traceback.print_exception(*exc_info)
del exc_info
Producing:
Traceback (most recent call last):
File "t.py", line 6, in <module>
raise TypeError("Oups!")
TypeError: Oups!
Few pitfalls with this though:
From the doc of
sys_info
:Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)
but, from the same doc:
Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.
On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:
import traceback
try:
raise TypeError("Oups!")
except Exception as err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_tb(err.__traceback__)
... will display:
File "e3.py", line 4, in <module>
raise TypeError("Oups!")
这篇关于如何打印完整的追溯而不停止程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!