python shell 继承 环境变量_Python subprocess shell 丢失环境变量 | 学步园

2023-05-16

问题:

今天遇到一个问题,我用一个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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python shell 继承 环境变量_Python subprocess shell 丢失环境变量 | 学步园 的相关文章

随机推荐