Python subprocess shell 丢失环境变量
2013-11-19 20:54
387 查看
问题:
今天遇到一个问题,我用一个python module通过subprocess以shell的方式调用另一个python module,结果导致丢失环境变量。事实上,无论是python还是java,还是cronjob,都会遇到这个问题。也就是通过终端调用另一个组件时,会遇到丢失环境变量的问题。
解决方案:
1. cmd = "alias python='python2.6'\npython -V"2. cmd = "source /home/group_aso/.bash_profile\npython -V"
两者并无本质上的区别。
需要特别指出的是,与shell不同,这里需要使用"\n"而不是";"
代码:
import sys, subprocess def exec_cmd(cmd): """Run shell command""" p = subprocess.Popen(cmd,stdin = subprocess.PIPE, \ stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True) log_content = p.communicate()[0] return p.returncode, log_content def main(): # Init # current_module_home = sys.path[0] # Call proxy module # cmd = "python -V" cmd_code, cmd_log = exec_cmd(cmd) print cmd_code print cmd_log if cmd_code != 0: print "%s: Failed running command: %s" % (sys.argv[0], cmd) sys.exit(-1) if __name__ == '__main__': main()
结果对比:
1. cmd="python -V"[group_aso@sm134 pythonCrawler]$ python test.py 0 Python 2.4.3
2. cmd = "alias python='python2.6'\npython -V"
[group_aso@sm134 pythonCrawler]$ python test.py 0 Python 2.6.5
3. cmd = "source /home/group_aso/.bash_profile\npython -V"
[group_aso@sm134 pythonCrawler]$ python test.py 0 Python 2.6.5
相关文章推荐
- python中 subprocess shell=False 与shell=True的区别
- python 调用 shell 时 设置环境变量
- Python subprocess shell 编程规范
- Python执行shell脚本的几种方式(最好用subprocess.Popen来替代os.system)
- Python subprocess shell 编程规范
- Python subprocess执行持续输出shell命令的控制
- Python subprocess,Linux下执行shell命令
- python3 获得shell的输出内容(subprocess.getstatusoutput)
- 利用python执行shell脚本 并动态传参 及subprocess基本使用
- 同一台PC安装了多版本python,且均配置了环境变量,pip list的时候提示:failed to create process
- python subprocess参数shell=True踩到的坑
- 如何结束一个python启动的shell子进程(How to terminate a python subprocess launched with shell=True)
- python3在win8下环境变量设置
- 把Python安装路径导入到系统环境变量中
- Python读取环境变量的方法和自定义类分享
- linux设置python环境变量
- 【python】环境变量的配置
- linux脚本编写基础(环境变量、shell流程控制)
- 8.6-8.9 管道符和作业控制、shell变量,环境变量
- shell小记-测试环境变量是否被设置