当我捕获异常时,如何获取类型、文件和行号?
捕获一个打印如下的异常:
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
Catching an exception that would print like this:
Traceback (most recent call last):
File "c:/tmp.py", line 1, in <module>
4 / 0
ZeroDivisionError: integer division or modulo by zero
I want to format it into:
ZeroDivisonError, tmp.py, 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
来源(Py v2.7.3)traceback.format_exception() 和调用/相关函数有很大帮助。 尴尬的是,我总是忘记阅读源代码。 我只是在徒劳地搜索类似细节后才这样做的。 一个简单的问题,“如何为异常重新创建与 Python 相同的输出,并具有所有相同的细节?” 这将使任何人 90% 以上都能找到他们想要的东西。 很沮丧,我想出了这个例子。 我希望它对其他人有帮助。 (这确实对我有帮助!;-)
对此查询的具体回答:
Source (Py v2.7.3) for traceback.format_exception() and called/related functions helps greatly. Embarrassingly, I always forget to Read the Source. I only did so for this after searching for similar details in vain. A simple question, "How to recreate the same output as Python for an exception, with all the same details?" This would get anybody 90+% to whatever they're looking for. Frustrated, I came up with this example. I hope it helps others. (It sure helped me! ;-)
In specific answer to this query:
对我有用的最简单的形式。
输出
Simplest form that worked for me.
Output
这是显示发生异常的行号的示例。
Here is an example of showing the line number of where exception takes place.
没有任何导入,但也不递归到导入的模块中:
$ python3 /tmp/example.py
TypeError /tmp/example.py 2
重申一下,这不能跨
导入
或模块工作,所以如果您导入X; 尝试: X.example();
那么文件名和行号将指向包含X.example()
的行,而不是内出现错误的行 em>X.example()
。 如果有人知道如何轻松地从最后一个堆栈跟踪行获取文件名和行号(我期望类似e[-1].filename
的东西,但没有这样的运气),请改进这个答案。Without any imports, but also not recursing into imported modules:
$ python3 /tmp/example.py
TypeError /tmp/example.py 2
To reiterate, this does not work across
import
s or modules, so if you doimport X; try: X.example();
then the filename and line number will point to the line containingX.example()
instead of the line where it went wrong withinX.example()
. If anyone knows how to easily get the file name and line number from the last stack trace line (I expected something likee[-1].filename
, but no such luck), please improve this answer.您无需导入回溯即可实现此目的:
输出:
You could achieve this without having to import traceback:
Output:
这就是我用来获取文件名的方法。
总而言之,我创建了一个页面来显示错误。 出现异常时返回此值。
发生异常时的外观:
This is what I used to get the file name.
To sum it, I created a page to show errors. Return this on exception.
How it looks in case an exception occurs: