[英]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 foo
和export 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 export
在
bash
- 您可以使用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.