Os.getenv returns None instead of the correct value

I have complex software that I cannot publish, and I do not have a concrete working example. I will try to explain the problem, maybe someone has come across this before.

In the Linux shell, I defined an environment variable:

> export MY_TEST_ENV=4711 > echo $MY_TEST_ENV > 4711 

In complex code, I want to get this variable with

 print os.getenv('MY_TEST_ENV') 

which always returns None . If I create a test script to test this behavior, even with classes in different files, I always get the desired behavior, for example, os.getenv('MY_TEST_ENV') returns the correct value 4711 .

The code is launched using sudo .

Any ideas what could be the reason?

+10
source share
1 answer

Most likely, the way you invoke the Python process causes you to lose the environment. If you export a variable to a running shell, and immediately after that call the Python process in question in the same shell, this environment variable must be available for this Python process. To help you debug this problem: instead of the code in question ( print os.getenv('my...') ), print the entire environment using print os.environ . From the result, you can conclude what happened to your environment.

+7
source

All Articles