Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.getenv returns None instead correct value [closed]

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?

like image 867
Alex Avatar asked Sep 11 '12 10:09

Alex


People also ask

What does Getenv return?

The getenv() function returns a pointer to the string containing the value for the specified varname in the current environment. If getenv() cannot find the environment string, NULL is returned, and errno is set to indicate the error.

Why would Getenv return null?

If the varname is not found, getenv() returns a NULL pointer. The returned value is NULL if the given variable is not currently defined.

Can system Getenv return null?

java - System. getenv() returns null when the environment variable exists - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

How do I check if an environment variable exists in Python?

# Checking if an Environment Variable Exists in Python import os if 'USER' in os. environ: print('Environment variable exists! ') else: print('Environment variable does not exist. ') # Returns: # Environment variable exists!


1 Answers

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.

like image 176
Dr. Jan-Philip Gehrcke Avatar answered Sep 19 '22 01:09

Dr. Jan-Philip Gehrcke