52

我在 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变量:

$ 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

$ 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

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

2 回答 2

97

Aha! the solution is simple!

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

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

  • it creates a variable in the shell
  • and exports it into the environment of the shell
  • the environment is passed to sub-processes of the shell.

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

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.

于 2013-09-28T19:08:44.263 回答
9

这些变量(bash 术语中的参数)不是环境变量。您想使用exportor将它们导出到环境中declare -x。请参阅有关 environment 的 bash 文档

于 2013-09-28T19:11:40.980 回答