[英]Python TypeError when printing traceback of AttributeError using traceback.print_exc()
A reproducible example:一个可重现的例子:
import traceback
X = None
try:
X.text
except (TypeError, AttributeError) as e:
traceback.print_exc(e)
This will raise an error at traceback.print_exc(e)
:这将在
traceback.print_exc(e)
引发错误:
TypeError: '>=' not supported between instances of 'AttributeError' and 'int'
Any suggestion why this happens?任何建议为什么会发生这种情况?
Based on the documentation: Python Docs - traceback module基于文档: Python Docs - traceback module
The first argument to traceback.print_exc isn't the exception, it is a depth limit of how many deep the traceback goes. traceback.print_exc 的第一个参数也不例外,它是回溯深度的深度限制。 You are hitting an exception within the traceback module itselse, since it expects the first argument to be a limit.
您在 traceback 模块中遇到了异常,因为它希望第一个参数是一个限制。
Your code needs to be:您的代码必须是:
import traceback
X = None
try:
X.text
except (TypeError, AttributeError) as e:
traceback.print_exc()
The exception data is kept as a thread global in sys.exc_info()
which is what traceback.print_exc()
uses.异常数据作为线程全局保存在
sys.exc_info()
中,这是traceback.print_exc()
使用的。
print_exc
doesn't take the exception object as an argument, it uses sys.exc_info()
to obtain exception information. print_exc
不以异常 object 作为参数,它使用sys.exc_info()
获取异常信息。 When you're passing it e
, it's interpreting it as a positional argument for limit
which expects a type int
.当您传递它
e
时,它会将其解释为limit
的位置参数,该参数需要一个int
类型。 I believe if you just remove the argument you'll get the result you're looking for.我相信,如果您只是删除参数,您将得到您正在寻找的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.