获取未在Python中定义的名称 [英] Getting the name which is not defined from NameError in python

查看:138
本文介绍了获取未在Python中定义的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如你所知,如果我们只是这样做:

 >>> a> 0 
追溯(最近的最后一次呼叫):
文件< pyshell#1>,第1行,< module>
a> 0
NameError:未定义名称'a'

有没有办法捕捉异常/错误,并从中提取值a。
我需要这个,因为我是 eval 使用一些动态创建的表达式,并且想要检索它们中没有定义的名称。



希望我清楚自己。
谢谢!
Manuel

解决方案

 >>> import re 
>>>尝试:
... a> 0
... except(NameError,),e:
... print re.findall(name(\w +)'定义,str(e))[0]
a

如果不想要使用正则表达式,您可以这样做一些这样的事情。

 >>> str(e).split(')[1] 
'a'


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

解决方案

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

这篇关于获取未在Python中定义的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆