如何从Python中的子进程获取环境 [英] How to get environment from a subprocess in Python

查看:150
本文介绍了如何从Python中的子进程获取环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一个python程序来调用一个进程,但是这个进程需要一些由另一进程设置的特定环境变量。如何获取第一个进程环境变量将其传递给第二个进程?



这是程序的样子:

  import subprocess 

subprocess.call(['proc1'])#this set env。 proc2
的子变量subprocess.call(['proc2'])#这个必须有env。由proc1设置的变量工作

但是进程不共享相同的环境。请注意,这些程序不是我的(第一个是大而丑的.bat文件,第二个是专有软件),所以我不能修改它们(好的,我可以从.bat提取我需要的所有,但它是非常combersome )



注意:我正在使用Windows,但我更喜欢跨平台的解决方案(但我的问题不会发生在类似Unix的...) / p>

解决方案

由于您显然在Windows中,您需要Windows答案。



创建包装器批处理文件,例如。 run_program.bat,并运行两个程序:

  @echo off 
调用proc1.bat
proc2

该脚本将运行并设置其环境变量。两个脚本都在相同的解释器(cmd.exe实例)中运行,所以在执行prog2时,变量prog1.bat设置将被设置。



不是很漂亮,但它会工作。



(Unix人,你可以在一个bash脚本中做同样的事情:source file.sh。) / p>

I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second?

This is what the program look like:

import subprocess

subprocess.call(['proc1']) # this set env. variables for proc2
subprocess.call(['proc2']) # this must have env. variables set by proc1 to work

but the to process don't share the same environment. Note that these programs aren't mine (the first is big and ugly .bat file and the second a proprietary soft) so I can't modify them (ok, I can extract all that I need from the .bat but it's very combersome).

N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)

解决方案

Since you're apparently in Windows, you need a Windows answer.

Create a wrapper batch file, eg. "run_program.bat", and run both programs:

@echo off
call proc1.bat
proc2

The script will run and set its environment variables. Both scripts run in the same interpreter (cmd.exe instance), so the variables prog1.bat sets will be set when prog2 is executed.

Not terribly pretty, but it'll work.

(Unix people, you can do the same thing in a bash script: "source file.sh".)

这篇关于如何从Python中的子进程获取环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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