How to get environment from a subprocess?(如何从子进程中获取环境?)
问题描述
我想通过python程序调用一个进程,但是,这个进程需要一些由另一个进程设置的特定环境变量.如何获取第一个进程环境变量以将它们传递给第二个?
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?
这是程序的样子:
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 中提取我需要的所有东西,但它非常精巧).
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).
注意:我使用的是 Windows,但我更喜欢跨平台解决方案(但我的问题不会发生在类 Unix 上......)
N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)
推荐答案
既然你显然是在 Windows 中,你需要一个 Windows 答案.
Since you're apparently in Windows, you need a Windows answer.
创建一个包装批处理文件,例如.run_program.bat",然后运行两个程序:
Create a wrapper batch file, eg. "run_program.bat", and run both programs:
@echo off
call proc1.bat
proc2
脚本将运行并设置其环境变量.两个脚本都在同一个解释器(cmd.exe 实例)中运行,因此 prog1.bat 设置的变量 将在 prog2 执行时设置.
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 人,你可以在 bash 脚本中做同样的事情:source file.sh".)
(Unix people, you can do the same thing in a bash script: "source file.sh".)
这篇关于如何从子进程中获取环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从子进程中获取环境?


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01