`
nbkangta
  • 浏览: 424465 次
  • 性别: Icon_minigender_1
  • 来自: 宁波
社区版块
存档分类
最新评论

Python如何输出环境变量

 
阅读更多

最近项目进展顺利,编码上面没干什么事情,就学起了Python

 

在wxpython遇到一个问题,ubuntu 12.04下面MenuBar没办法显示

查询了伟大的stackoverflow,证明是Ubuntu的一个bug,在调用脚本前设置环境变量就可以解决

export UBUNTU_MENUPROXY=0

 

就想着集成到脚本里面去,自然的想到如下代码

import os

os.system("export UBUNTU_MENUPROXY=0")

 

但是it doesn't work! why? 还是求助 stackoverflow,看到如下内容

export is a command that you give directly to the shell (e.g. bash), to tell it to add or modify one of its environment variables. You can't change your shell's environment from a child process (such as Python), it's just not possible.

Here's what's happening with you try os.system('export MY_DATA="my_export"')...

/bin/bash process, command `python yourscript.py` forks python subprocess
 |_
   /usr/bin/python process, command `os.system()` forks /bin/sh subprocess
    |_
      /bin/sh process, command `export ...` changes local environment
When the bottom-most /bin/sh subprocess finishes running your export ... command, then it's discarded, along with the environment that you have just changed.

 

大牛们说了,这段的线程树是这样的

/bin/bash -> /usr/bin/python -> /bin/sh

export 是在/bin/sh中执行的,执行完成后就退出这个子线程了,export了解的话就知道export是export到当前线程,对父线程不可见,于是在/usr/bin/python中当然起不到作用?

正确的设置方法是? 很简单:

import os
os.environ['UBUNTU_MENUPROXY'] = 0

 

搞定

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics