捕获异常时,如何获取类型、文件和行号?
捕获一个异常,它的打印格式像这样:
Traceback (most recent call last):
File "c:/tmp.py", line 1, in <module>
4 / 0
ZeroDivisionError: integer division or modulo by zero
我想把它格式化成:
ZeroDivisonError, tmp.py, 1
8 个回答
55
来源(Python版本2.7.3)对于traceback.format_exception()和相关函数的理解非常有帮助。尴尬的是,我总是忘记去查看源代码。这次我是在找不到类似信息后才去看的。一个简单的问题是:“如何重现Python抛出异常时的输出,确保所有细节都一样?”这个问题可以帮助大多数人找到他们想要的答案。感到沮丧时,我想出了这个例子。希望能帮助到其他人。(这确实帮了我!;-)
import sys, traceback
traceback_template = '''Traceback (most recent call last):
File "%(filename)s", line %(lineno)s, in %(name)s
%(type)s: %(message)s\n''' # Skipping the "actual line" item
# Also note: we don't walk all the way through the frame stack in this example
# see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
# (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)
try:
1/0
except:
# http://docs.python.org/2/library/sys.html#sys.exc_info
exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default
'''
Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
or if we do not delete the labels on (not much) older versions of Py, the
reference we created can linger.
traceback.format_exc/print_exc do this very thing, BUT note this creates a
temp scope within the function.
'''
traceback_details = {
'filename': exc_traceback.tb_frame.f_code.co_filename,
'lineno' : exc_traceback.tb_lineno,
'name' : exc_traceback.tb_frame.f_code.co_name,
'type' : exc_type.__name__,
'message' : exc_value.message, # or see traceback._some_str()
}
del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
# This still isn't "completely safe", though!
# "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
# with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
print
print traceback.format_exc()
print
print traceback_template % traceback_details
print
针对这个问题的具体回答:
sys.exc_info()[0].__name__, os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), sys.exc_info()[2].tb_lineno
337
这是我用过的最简单的有效形式。
import traceback
try:
print(4/0)
except ZeroDivisionError:
print(traceback.format_exc())
输出结果
Traceback (most recent call last):
File "/path/to/file.py", line 51, in <module>
print(4/0)
ZeroDivisionError: division by zero
Process finished with exit code 0
534
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。比如说,当用户点击一个按钮时,我们希望程序能够做出反应。这个过程通常涉及到“事件处理”。
事件处理就是当某个事件发生时,程序会执行预先设定好的代码。比如,用户点击按钮、移动鼠标或者按下键盘上的某个键,这些都可以被视为事件。
为了让程序知道该如何处理这些事件,我们需要定义“事件监听器”。事件监听器就像是一个守卫,它会一直关注特定的事件,一旦事件发生,就会触发相应的代码执行。
简单来说,事件处理和事件监听器的作用就是让程序能够对用户的操作做出反应,从而实现交互性。这样,用户在使用程序时,就能得到更好的体验。
import sys, os
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)