如何检查变量是否存在?

时间:2011-08-01 08:14:15

标签: python arrays variables

我想检查名为component +“_STATUS”或+“_DESC”的变量是否存在。

我尝试了以下内容,但它不起作用。所以,这是我的代码:

Components = ['SAVE_DOCUMENT', \
'GET_DOCUMENT', \
'DVK_SEND', \
'DVK_RECEIVE', \
'GET_USER_INFO', \
'NOTIFICATIONS', \
'ERROR_LOG', \
'SUMMARY_STATUS']

for Component in Components:
    try:
        eval(Component + "_STATUS")
        eval(Component + "_DESC")
    except NameError:
        print "Missing component " + Component + " information!"
        sys.exit(StateUnknown)

2 个答案:

答案 0 :(得分:4)

我可能错了,但我认为您可以通过以下方式执行此操作(无需使用eval - 因为使用它不是很好):

Components = ['SAVE_DOCUMENT', 'GET_DOCUMENT', 'DVK_SEND', 'DVK_RECEIVE', 'GET_USER_INFO', 'NOTIFICATIONS', 'ERROR_LOG', 'SUMMARY_STATUS']
missed = [x for x in Components if x + "_STATUS" not in locals() or x + "_DESC" not in locals()]
if missed:
    print "Missing components: {0:}".format(missed)
    sys.exit(StateUnknown)        

如果您需要在本地范围内检查变量在线状态,可以使用locals(),否则可以使用globals()

答案 1 :(得分:2)

>>> f = 1
>>> globals()
{'__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', 'f': 1, '__doc__': None, '__package__': None}
>>> 'f' in globals()
True