Chris_vr Chris_vr - 1 year ago 99
Python Question

NameError: global name 'deployment_mode' is not defined

I have following code in python.This code is part of bigger code.
It worked earlier.But recently it started complaining.

I ma calling like this

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

Its legacy code and worked well in past.It looks odd to me as


never executed so the deployment_mode never initialized.

import os

def _register_cassandra_service(isReRegister):

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


ubuntu@vikdevtest-deploy:/opt/cisco/vms-installer/scripts$ python -c "import test; test._register_cassandra_service(True)"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "", line 5, in _register_cassandra_service
NameError: global name 'deployment_mode' is not defined

Please help me on this

Answer Source

Python has no concept of a main() function that is the entry point for a module. If you need the code in main() to always run, then either explicitly call that function or move the code in it to the global namespace.

You can use a __name__ == '__main__' test to only run code when your module is used as a script (as the script file run by Python is internally given the module name '__main__'), but that doesn't apply here as you are running a -c script instead.

The code, as posted, could never have worked before now either. If you ever invoked it directly with python test, then look for a if __name__ == '__main__': block to see what code is run there; that code won't run when you import the script with import test.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download