Home > Mobile >  Python os.environ doesn't show empty environment variables
Python os.environ doesn't show empty environment variables

Time:09-27

After an environment variable is exported and set to empty, I can't get its value in Python with os.environ. Is it expected?

Examples:

## export TEST_ENV_VAR
(base) ➜  Code export | grep TEST_ENV_VAR
TEST_ENV_VAR=''
(base) ➜  Code python
Python 3.8.12 (default, Oct 12 2021, 13:49:34) 
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> 'TEST_ENV_VAR' in os.environ
False

## export TEST_ENV_VAR=''
(base) ➜  Code export | grep TEST_ENV_VAR
TEST_ENV_VAR=''
(base) ➜  Code python 
Python 3.8.12 (default, Oct 12 2021, 13:49:34) 
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> 'TEST_ENV_VAR' in os.environ
True

## export TEST_ENV_VAR='TEST'
(base) ➜  Code export | grep TEST_ENV_VAR
TEST_ENV_VAR=TEST
(base) ➜  Code python                    
Python 3.8.12 (default, Oct 12 2021, 13:49:34) 
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> 'TEST_ENV_VAR' in os.environ
True

The three samples above run in three different new terminals. I modified the .zshrc file to export different values. What's the difference between export foo and export foo=''?

CodePudding user response:

There is a difference between "Shell variables" and "Environment Variables" - see here - A shell variable is only available to the shell setting it whereas an environment variable is available to all child processes as well.

In bash - you can get the list of environment variables with env, and add to the environment variables with export

SHELL_VAR="10"
env | grep SHELL_VAR # No result
export ENV_VAR=100
env | grep ENV_VAR # ENV_VAR=100

Python shell (child process) picks the environment variables when you try an os.environ

'SHELL_VAR' in os.environ # False
'ENV_VAR' in os.environ # True

CodePudding user response:

The issue is the way you are defining your variables.

When you just do:

export FOO

no variable is actually exported unless FOO has been defined previously:

FOO=''
export FOO

or concomitantly:

export FOO=''

If FOO appears in env | grep FOO, it should appear in os.environ.

  • Related