python 在python中从NameError获取未定义的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2270795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:14:00  来源:igfitidea点击:

Getting the name which is not defined from NameError in python

pythonexception-handlingdynamic-dataexpressionnameerror

提问by Manuel Aráoz

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.

有没有办法捕获异常/错误并从中提取值“a”。我需要这个,因为我正在使用eval一些动态创建的表达式,并且想要检索未在其中定义的名称。

Hope I made myself clear. Thanks! Manuel

希望我说清楚了。谢谢!曼努埃尔

采纳答案by John La Rooy

>>> 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'

回答by kepkin

>>> 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.

您可以解析 '' 的异常字符串以提取值。

回答by dansalmo

No import exceptionsneeded in Python 2.x

没有import exceptions必要在Python 2.x的

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

You assign the reference for 'a' as such:

您为 'a' 分配引用,如下所示:

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