我想通过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文件中提取环境变量。享受吧。
因此,要回答您的问题,您需要创建一个.py文件,该文件执行以下操作:
正如您所说,进程不共享环境,因此您字面上的要求是不可能的,不仅在Python中,而且在任何编程语言中都是不可能的。
您可以将环境变量放入文件或管道中,然后
后者需要proc2的合作;前者需要在proc2启动之前知道变量。
既然你显然是在Windows里,你需要Windows的答案。
创建包装批处理文件,例如“run_program.bat”,并运行两个程序:
脚本将运行并设置其环境变量。两个脚本在同一个解释器(cmd.exe实例)中运行,因此在执行prog2时,变量prog1.bat sets将被设置为。
不是很漂亮,但会有用的。
(Unix用户,可以在bash脚本中执行相同的操作:“source file.sh”。)
相关问题 更多 >
编程相关推荐