os.getenv和os.environ看不到我的bash shell的环境变量 [英] python - os.getenv and os.environ don't see environment variables of my bash shell

查看:381
本文介绍了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中的变化:

$ 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的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆