python - os.getenv 和 os.environ 看不到我的 bash shell 的环境变量

问题描述

我在 ubuntu 13.04,bash,python2.7.4

I am on ubuntu 13.04, bash, python2.7.4

解释器看不到我设置的变量.

这是一个例子:

$ echo $A
5
$ python -c 'import os; print os.getenv( "A" )'
None
$ python -c 'import os; print os.environ[ "A" ]'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'A'

但是 PATH 变量一切正常:

But everything works fine with the PATH variable:

$ echo $PATH 
/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
$ python -c 'import os; print os.getenv("PATH")'
/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

它会注意到 PATH 的变化:

And it notices changes in PATH:

$ PATH="/home/alex/tests/:$PATH"
$ echo $PATH 
/home/alex/tests/:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
$ python -c 'import os; print os.getenv("PATH")'
/home/alex/tests/:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

可能出了什么问题?

PS 使用 $PYTHONPATH 时出现问题:

PS the problem comes when using $PYTHONPATH:

$ python -c 'import os; print os.getenv("PYTHONPATH")'
None


解决方案

啊哈!解决方法很简单!

Aha! the solution is simple!

我用普通的 $ A=5 命令设置变量;当你使用 $ export B="foo" 一切都很好.

I was setting variables with plain $ A=5 command; when you use $ export B="foo" everything is fine.

那是 because export 使变量可用于子进程:

That is because export makes the variable available to sub-processes:

  • 它在 shell 中创建一个变量
  • 并导出到shell环境中
  • 环境被传递给 shell 的子进程.

Plain $ A="foo" 只是在 shell 中创建变量,不对环境做任何事情.

Plain $ A="foo" just creates variables in the shell and doesn't do anything with the environment.

从 shell 调用的解释器从父 shell 获取它的环境.所以真的应该先将变量导出到环境中.

The interpreter called from the shell obtains its environment from the parent -- the shell. So really the variable should be exported into the environment before.

相关文章