开发者

Getting the name which is not defined from NameError in python

开发者 https://www.devze.com 2022-12-20 01:59 出处:网络
As you know, if we simply do: >>> a > 0 Traceback (most recent call last): File \"<pyshell#1>\", line 1, in <module>

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 my开发者_运维百科self clear. Thanks! Manuel


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号