Python 为多个进程创建 shell

Python create shell for several processes

我在 python 在 Windows 中使用 subprocess.call() 执行了多个命令,但是对于每个命令,我都需要在调用正确的命令之前使用环境设置执行批处理文件,它看起来像这样

subprocess.call(precommand + command)

有没有办法在 python 中 "create" shell 只执行一次批处理文件,而 shell 命令将执行多次?

您需要分别获取每个命令的输出吗?如果否 - 您可以使用 &&、|| 传达这些命令或;

cd dir && cp test1 test2 && cd -
  1. 将命令写入 bat-file (tempfile.NamedTemporaryFile())
  2. 运行 bat-file (subprocess.check_call(bat_file.name))

(未测试):

#!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
import tempfile

with tempfile.NamedTemporaryFile('w', suffix='.bat', delete=False) as bat_file:
    print(precommand, file=bat_file)
    print(command, file=bat_file)
rc = subprocess.call(bat_file.name)
os.remove(bat_file.name)
if rc != 0:
    raise subprocess.CalledProcessError(rc, bat_file.name)