Getting the name which is not defined from NameError in python

后端 未结 3 1095
悲哀的现实
悲哀的现实 2021-01-17 22:51

As you know, if we simply do:

>>> a > 0
Traceback (most recent call last):
  File \"\", line 1, in 
    a > 0
N         


        
3条回答
  •  无人共我
    2021-01-17 23:25

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

提交回复
热议问题