我想通过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".)
这篇关于如何从子进程中获取环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!