2016-11-02 123 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()

相关问题