如何从子流程中获取环境? [英] How to get environment from a subprocess?

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

问题描述

我想通过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

,但要处理的进程不共享相同的环境.请注意,这些程序不是我的(第一个程序大而丑陋的.bat文件,第二个是专有软件),因此我无法对其进行修改(好的,我可以从.bat中提取所有我需要的文件,但是它非常繁琐) ).

N.B .:我正在使用Windows,但我更喜欢跨平台的解决方案(但在类似Unix的系统上不会发生我的问题……)

解决方案

由于您显然在Windows中,因此需要Windows答案.

创建包装批处理文件,例如. "run_program.bat",然后运行两个程序:

@echo off
call proc1.bat
proc2

该脚本将运行并设置其环境变量.这两个脚本都在同一个解释器(cmd.exe实例)中运行,因此在执行prog2时将设置变量prog1.bat设置 .

不是很漂亮,但是会起作用.

(Unix上的人,您可以在bash脚本中执行相同的操作:"source file.sh".)

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".)

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

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