我想通过python程序调用一个进程,但是,这个进程需要一些由另一个进程设置的特定环境变量。如何获取第一个进程环境变量以将它们传递给第二个?
这是程序的样子:
import subprocess
subprocess.call(['proc1']) # this set env. variables for proc2
subprocess.call(['proc2']) # this must have env. variables set by proc1 to work
但是 to 进程不共享相同的环境。请注意,这些程序不是我的(第一个是又大又丑的 .bat 文件,第二个是专有软件)所以我不能修改它们(好吧,我可以从 .bat 中提取我需要的所有东西,但它非常精巧)。
注意:我使用的是 Windows,但我更喜欢跨平台解决方案(但我的问题不会发生在类 Unix 上......)
最佳答案
这是一个示例,说明如何在不创建包装脚本的情况下从批处理或 cmd 文件中提取环境变量。享受吧。
from __future__ import print_function
import sys
import subprocess
import itertools
def validate_pair(ob):
try:
if not (len(ob) == 2):
print("Unexpected result:", ob, file=sys.stderr)
raise ValueError
except:
return False
return True
def consume(iter):
try:
while True: next(iter)
except StopIteration:
pass
def get_environment_from_batch_command(env_cmd, initial=None):
"""
Take a command (either a single command or list of arguments)
and return the environment created after running that command.
Note that if the command must be a batch file or .cmd file, or the
changes to the environment will not be captured.
If initial is supplied, it is used as the initial environment passed
to the child process.
"""
if not isinstance(env_cmd, (list, tuple)):
env_cmd = [env_cmd]
# construct the command that will alter the environment
env_cmd = subprocess.list2cmdline(env_cmd)
# create a tag so we can tell in the output when the proc is done
tag = 'Done running command'
# construct a cmd.exe command to do accomplish this
cmd = 'cmd.exe /s /c "{env_cmd} && echo "{tag}" && set"'.format(**vars())
# launch the process
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=initial)
# parse the output sent to stdout
lines = proc.stdout
# consume whatever output occurs until the tag is reached
consume(itertools.takewhile(lambda l: tag not in l, lines))
# define a way to handle each KEY=VALUE line
handle_line = lambda l: l.rstrip().split('=',1)
# parse key/values into pairs
pairs = map(handle_line, lines)
# make sure the pairs are valid
valid_pairs = filter(validate_pair, pairs)
# construct a dictionary of the pairs
result = dict(valid_pairs)
# let the process finish
proc.communicate()
return result
因此,要回答您的问题,您需要创建一个 .py 文件,该文件执行以下操作:
env = get_environment_from_batch_command('proc1')
subprocess.Popen('proc2', env=env)
关于python - 如何从子进程中获取环境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1214496/