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?
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.
If the varname is not found, getenv() returns a NULL pointer. The returned value is NULL if the given variable is not currently defined.
java - System. getenv() returns null when the environment variable exists - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
# 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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With