问题描述
我正在使用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
中的变化:
$ 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
推荐答案
啊!解决方案很简单!
我用普通的$ A=5
命令设置变量;当您使用$ export B="kkk"
时,一切都很好.
I was setting variables with plain $ A=5
command; when you use $ export B="kkk"
everything is fine.
That is because export
makes the variable available to sub-processes:
- 它在外壳中创建一个变量
- 并将导出到外壳的
environment
- 列表
environment
被传递到Shell的子进程.
- it creates a variable in the shell
- and exports it into the
environment
of the shell - the list
environment
is passed to sub-processes of the shell.
普通$ A="kkk"
只是在shell中创建变量,而对environment
不做任何事情.
Plain $ A="kkk"
just creates variables in the shell and doesn't do anything with the environment
.
从shell调用的解释器从父级shell获取environment
.因此,实际上应该先将变量导出到environment
中.
The interpreter called from the shell obtains it's environment
from the parent -- the shell. So really the variable should be exported into the environment
before.
这篇关于os.getenv和os.environ看不到我的bash shell的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!