从Python中的NameError获取未定义的名称
如您所知,如果我们简单地这样做:
>>> a > 0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a > 0
NameError: name 'a' is not defined
是否有一种方法可以捕获异常/错误并从中提取值“a”。 我需要这个,因为我正在评估一些动态创建的表达式,并且想要检索其中未定义的名称。
希望我说清楚了。 谢谢! 曼努埃尔
As you know, if we simply do:
>>> a > 0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a > 0
NameError: name 'a' is not defined
Is there a way of catching the exception/error and extracting from it the value 'a'.
I need this because I'm eval
uating some dynamically created expressions, and would like to retrieve the names which are not defined in them.
Hope I made myself clear.
Thanks!
Manuel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Python 2.x 中不需要
导入异常
您可以这样分配“a”的引用:
No
import exceptions
needed in Python 2.xYou assign the reference for 'a' as such:
如果你不想使用正则表达式,你可以这样做
If you don't want to use regex, you could do something like this instead
您可以解析异常字符串“”以提取值。
You can parse exceptions string for '' to extract value.