2011-08-01 159 views
1

我想檢查名爲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) 

回答

4

我可能是錯的,但我認爲你可以做到這一點通過以下方式(不usign 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()

+0

就像一個魅力! :) – Marko

+0

@Marko - 謝謝你)希望這會有所幫助 –

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