从Python中的NameError获取未定义的名称

发布于 2024-08-21 11:23:41 字数 309 浏览 8 评论 0原文

如您所知,如果我们简单地这样做:

>>> 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 evaluating 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深海不蓝 2024-08-28 11:23:42

Python 2.x 中不需要导入异常

>>> try:
...     a > 0
... except NameError as e:
...     print e.message.split("'")[1]
...
a
>>>

您可以这样分配“a”的引用:

>>> try:
...     a > 0
... except NameError as e:
...     locals()[e.message.split("'")[1]] = 0
...
>>> a
0

No import exceptions needed in Python 2.x

>>> try:
...     a > 0
... except NameError as e:
...     print e.message.split("'")[1]
...
a
>>>

You assign the reference for 'a' as such:

>>> try:
...     a > 0
... except NameError as e:
...     locals()[e.message.split("'")[1]] = 0
...
>>> a
0
莫言歌 2024-08-28 11:23:41
>>> import re
>>> try:
...     a>0
... except (NameError,),e:
...     print re.findall("name '(\w+)' is not defined",str(e))[0]
a

如果你不想使用正则表达式,你可以这样做

>>> str(e).split("'")[1]
'a'
>>> import re
>>> try:
...     a>0
... except (NameError,),e:
...     print re.findall("name '(\w+)' is not defined",str(e))[0]
a

If you don't want to use regex, you could do something like this instead

>>> str(e).split("'")[1]
'a'
假装爱人 2024-08-28 11:23:41
>>> import exceptions
>>> try:
...     a > 0
... except exceptions.NameError, e:
...     print e
... 
name 'a' is not defined
>>> 

您可以解析异常字符串“”以提取值。

>>> import exceptions
>>> try:
...     a > 0
... except exceptions.NameError, e:
...     print e
... 
name 'a' is not defined
>>> 

You can parse exceptions string for '' to extract value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文