2016-11-02 126 views
-1

我在Python中有以下代碼。這是更大的代碼庫的一部分。 它曾經工作過,但最近開始抱怨。NameError:全局名稱'deployment_mode'未定義

我打電話test.py這樣的:

python -c "import test; test._register_cassandra_service(True)" 

這是遺留代碼,並在過去行之有效。這看起來很奇怪我爲

print('jjj') 

從來沒有執行,所以deployment_mode永遠不會初始化。

的代碼如下:

test.py

import os 

def _register_cassandra_service(isReRegister): 
    print('hhhhhhhhhhhhhhhhhhhh') 
    print(deployment_mode) 

def main(): 
    global deployment_mode 
    print('jjj') 
    deployment_mode = os.environ.get('DEPLOY_MODE') 

錯誤

[email protected]:/opt/cisco/vms-installer/scripts$ python -c "import test; test._register_cassandra_service(True)" 
hhhhhhhhhhhhhhhhhhhh 
Traceback (most recent call last): 
    File "<string>", line 1, in <module> 
    File "test.py", line 5, in _register_cassandra_service 
    print(deployment_mode) 
NameError: global name 'deployment_mode' is not defined 

任何幫助,將不勝感激。

+1

'main()'不會自動運行。如果你需要它運行,你需要調用它。 – khelwood

+0

@khelwood任何想法如何工作更早 –

+0

@Chris_vr:你明確調用'main()'或沒有把它放在函數中? 'main()'永遠不會自動調用。 –

回答

1

Python沒有作爲模塊入口點的main()函數的概念。如果您需要main()中的代碼,則始終運行,然後顯式調用該函數或將代碼移入全局名稱空間。

您可以使用__name__ == '__main__'測試僅在模塊用作腳本時運行代碼(因爲由Python運行的腳本文件在內部被賦予模塊名稱'__main__'),但在運行時不適用改爲-c腳本。

發佈的代碼在此之前可能無法工作。如果您曾用python test直接調用它,然後查找if __name__ == '__main__':塊以查看在那裏運行的代碼;當您使用import test導入腳本時,代碼將不會運行

1

您必須先致電main(),然後致電_register_cassandra_service(),以便設置deployment_mode的值。

您還可以撥打電話main()_register_cassandra_service(),因爲它取決於main()

相關問題