如何在 subprocess.Popen() 中使用现有的环境变量 [英] How to use an existing Environment variable in subprocess.Popen()

查看:218
本文介绍了如何在 subprocess.Popen() 中使用现有的环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景

在我的 python 脚本中,我需要将可执行文件作为子进程运行,其中包含可执行文件所期望的 x 个命令行参数.

In my python script I need to run an executable file as a subprocess with x number of command line parameters which the executable is expecting.

示例:

  • EG 1: myexec.sh param1 param2
  • EG 2:myexec.sh param1 $MYPARAMVAL

可执行文件和参数未知,因为它们是在运行时从外部源 (xml config) 配置和检索的.

The executable and parameters are not known as these are configured and retrieved from external source (xml config) at run time.

当参数是已知值(EG 1)并配置时,我的代码正在工作,但是期望参数可以是环境变量并配置为这样,应该在运行时解释.(EG 2)

My code is working when the parameter is a known value (EG 1) and configured, however the expectation is that a parameter could be an environment variable and configured as such, which should be interpreted at run time.(EG 2)

在下面的示例中,我使用 echo 作为 myexec.sh 的替代品来演示该场景.这是为了演示问题而简化的.cmdlst"是从配置文件构建的,该配置文件可以是具有任意数量参数和值的任何脚本,可以是值或环境变量.

In the example below I am using echo as a substitute for myexec.sh to demonstrate the scenario. This is simplified to demonstrate issue. 'cmdlst' is built from a configuration file, which could be any script with any number of parameters and values which could be a value or environment variable.

test1.py

import subprocess
import os

cmdlst = ['echo','param1','param2']

try:
    proc = subprocess.Popen(cmdlst,stdout=subprocess.PIPE)
    jobpid = proc.pid
    stdout_value, stderr_value = proc.communicate()
except (OSError, subprocess.CalledProcessError) as err:
    raise

print stdout_value

结果测试 1

python test1.py

--> 参数 1 参数 2

--> param1 param2

test2.py

import subprocess
import os

cmdlst = ['echo','param1','$PARAM']

try:
    proc = subprocess.Popen(cmdlst,stdout=subprocess.PIPE)
    jobpid = proc.pid
    stdout_value, stderr_value = proc.communicate()
except (OSError, subprocess.CalledProcessError) as err:
    raise

print stdout_value

结果测试 2

export PARAM=param2echo $PARAM

--> 参数 2python test2.py

--> param1 $PARAM

--> param1 $PARAM

我要求测试 2 产生与测试 1 相同的结果,考虑到 $PARAM 仅在运行时已知并且需要从当前环境中检索.

I require Test 2 to produce the same result as Test 1, considering that $PARAM would only be known at run-time and need to be retrieved from the current environment.

我欢迎你的建议.

推荐答案

您可以:

cmdlist = ['echo','param',os.environ["PARAM"]]

或者:

cmdlist = ['echo','param1','$PARAM']
proc = subprocess.Popen(cmdlist,stdout=subprocess.PIPE, env={'PARAM':os.environ['PARAM'])

这篇关于如何在 subprocess.Popen() 中使用现有的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆