2017-07-05 45 views
1

我露出一个系统环境变量说KEY1/etc/profile价值VALUE1(我知道,我知道,它可能是坏的)Python的获取系统环境变量的Linux

现在在我的壳,如果我做

$ echo $KEY1 
VALUE1 

但是当我做

$ python -c "import os; print os.environ.get('KEY1')" 
None 
$ 

为什么会是这样的情况?

+0

而不是保存在/ etc/profile中,您可以创建一个bash shell并将KEY1作为参数传递给python脚本。 –

+0

多种不同类型的应用程序正在使用它,因此无法将参数传递给python脚本。 –

回答

1

您可能没有导出变量。您可以将export视为将shell变量公开而非私有的方式。看看export man page

➜ ~ K=1  
➜ ~ echo $K 
1 
➜ ~ python -c "import os; print os.environ.get('K')" 
None 
➜ ~ export K=1 
➜ ~ python -c "import os; print os.environ.get('K')" 
1 
+0

我在'/ etc/profile'中添加了这个变量。这是环境变量的全球存储。我不必再输出它。 –

+1

即使你把它放在''/ etc/profile''中,你仍然需要这个''export''语句。如果你不这样做,它不适用于设置它的shell中的子进程。那么你在设置它时使用了“export”吗? –