Getting the name which is not defined from NameError in python

后端 未结 3 1094
悲哀的现实
悲哀的现实 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'
    
    0 讨论(0)
  • 2021-01-17 23:26

    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 讨论(0)
  • 2021-01-17 23:27
    >>> 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.

    0 讨论(0)
提交回复
热议问题