python - os.getenv and os.environ don't see environment variables of my bash shell

試著忘記壹切 提交于 2019-11-30 11:19:46

问题


I am on ubuntu 13.04, bash, python2.7.4

The interpreter doesn't see variables I set.

Here is an example:

$ 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'

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

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

What could be wrong?

PS the problem comes when using $PYTHONPATH:

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

回答1:


Aha! the solution is simple!

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:

  • 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.

Plain $ A="kkk" just creates variables in the shell and doesn't do anything with the 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.




回答2:


Those variables (parameters in bash terminology) are not environment variables. You want to export them into the environment, using export or declare -x. See the bash documentation on environment.



来源:https://stackoverflow.com/questions/19070615/python-os-getenv-and-os-environ-dont-see-environment-variables-of-my-bash-she

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!