简体   繁体   English

Python os.environ 不显示空环境变量

[英]Python os.environ doesn't show empty environment variables

After an environment variable is exported and set to empty, I can't get its value in Python with os.environ .导出环境变量并将其设置为空后,我无法使用os.environ在 Python 中获取其值。 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.我修改了 .zshrc 文件以导出不同的值。 What's the difference between export foo and export foo='' ? export fooexport foo=''有什么区别?

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. “Shell 变量”和“环境变量”之间存在差异 - 请参见此处- shell 变量仅适用于 shell 设置它,而环境变量也适用于所有子进程。

In bash - you can get the list of environment variables with env , and add to the environment variables with exportbash - 您可以使用env获取环境变量列表,并使用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 Python shell(子进程)在您尝试os.environ时选择环境变量

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

The issue is the way you are defining your variables.问题是您定义变量的方式。

When you just do:当你这样做时:

export FOO

nothing happens unless FOO has been defined previously :除非之前定义了FOO ,否则什么都不会发生:

FOO=''
export FOO

or concomitantly :同时

export FOO=''

If FOO appears in env | grep FOO如果FOO出现在env | grep FOO env | grep FOO , it should appear in os.environ . env | grep FOO ,它应该出现在os.environ中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM