5

在 Windows 上,我想在我的 python 脚本中使用第 3 方命令行工具假设它foobar.exe位于C:\Program Files (x86)\foobar. Foobar 附带一个额外的批处理文件init_env.bat,它将设置foobar.exe运行的 shell 环境。

我想写一个python脚本,它会先调用init_env.bat一次,然后再调用foobar.exe多次。但是,我所知道的所有机制(subprocessos.system和反引号)似乎都会为每次执行产生一个新进程。因此,调用init_env.bat是没有用的,因为它不会改变运行python脚本的进程的环境,因此每次后续调用都会foobar.exe失败,因为它的环境没有设置。

是否可以通过init_env.bat允许init_env.bat更改调用脚本进程环境的方式从 python 调用?

4

1 回答 1

5

Is it possible to call init_env.bat from python in a way that allows init_env.bat to alter the environment of the calling scripts process?

Not easily, although, if the init_env.bat is really simple, you could attempt to parse it, and make the changes to os.environ yourself.

Otherwise it's much easier to spawn it in a sub-shell, followed by a call to set to output the new environment variables, and parse the output from that.

The following works for me...

init_env.bat

@echo off
set FOO=foo
set BAR=bar

foobar.bat

@echo off
echo FOO=%FOO%
echo BAR=%BAR%

main.py

import sys, os, subprocess


INIT_ENV_BAT = 'init_env.bat'
FOOBAR_EXE = 'foobar.bat'


def init_env():
    vars = subprocess.check_output([INIT_ENV_BAT, '&&', 'set'], shell=True)
    for var in vars.splitlines():
        k, _, v = map(str.strip, var.strip().partition('='))
        if k.startswith('?'):
            continue
        os.environ[k] = v


def main():
    init_env()
    subprocess.check_call(FOOBAR_EXE, shell=True)
    subprocess.check_call(FOOBAR_EXE, shell=True)


if __name__ == '__main__':
    main()

...for which python main.py outputs...

FOO=foo
BAR=bar
FOO=foo
BAR=bar

Note that I'm only using a batch file in place of your foobar.exe because I don't have a .exe file handy which can confirm the environment variables are set.

If you're using a .exe file, you can remove the shell=True clause from the lines subprocess.check_call(FOOBAR_EXE, shell=True).

于 2013-07-12T14:44:33.930 回答