os.getenv returns None instead correct value [closed]
Asked Answered
W

1

14

I have a complex piece of software I am not able to post, nor do I have a concrete working example. I will try to explain the problem, maybe someone encountered this before.

On the Linux shell I have defined an environment variable:

> export MY_TEST_ENV=4711
> echo $MY_TEST_ENV
> 4711

Within the complex code I want to obtain 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, e.g., os.getenv('MY_TEST_ENV') returns the correct value 4711.

The code is started with sudo.

Any ideas what could be the reason?

Weswesa answered 11/9, 2012 at 10:10 Comment(4)
How are you running this "complex code"?Pastorship
Are the rest of the environment variables still there? How is the python process launched? If you start a process with the execve system call and do not fill in the environment variable, the child's environment is zeroed.Daiseydaisi
I knew the solution to my problem is trivial - because I run the python process as sudo! But I have not seen this solution until I was asked o how to run the code. Without sudo, I see the variable (but the rest of the code will not work, though).Weswesa
@Weswesa Remember that sudo starts a new shell with superuser privileges, and scrubs the environment according to the security policy. Using the -E (or --preserve-env) switch to sudo may cause MY_TEST_ENV to be retained, or maybe not again depending on the specifics of your system's security policy. Another route is to request someone with appropriate access to the system to inject the variable you want into root's environment by editing the appropriate initialization script.Stillwell
J
12

Most likely the way you invoke the Python process makes you lose the environment. If you export the variable within a running shell and, directly after that, invoke the Python process in question in the same shell, this environment variable should definitely be available to this Python process. To help you debugging this issue: instead of the code in question (print os.getenv('my...')), print the whole environment via print os.environ. From the result you should be able to infer what happened to your environment.

Jaddan answered 11/9, 2012 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.