Chris_vr Chris_vr - 1 month ago 15
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 test.py 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

print('jjj')


never executed so the deployment_mode never initialized.

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')


Error

ubuntu@vikdevtest-deploy:/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


Please help me on this

Answer

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.