Getting the name which is not defined from NameError in python

被刻印的时光 ゝ 提交于 2019-12-01 15:12:50

问题


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


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/2270795/getting-the-name-which-is-not-defined-from-nameerror-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!