python - os.getenv and os.environ don#39;t see environment variables of my bash shell(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.
这篇关于python - os.getenv 和 os.environ 看不到我的 bash shell 的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python - os.getenv 和 os.environ 看不到我的 bash shell 的环境变量


基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01