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 的环境变量
基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
