Getting the name which is not defined from NameError in python

梦想的初衷 提交于 2019-12-01 16:22:47
>>> 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!