我希望并行运行两个可执行文件a.exe和b.exe,一个接一个地调用。
我尝试的时候
os.system('a.exe')
#some code
os.system('b.exe')
b.exe是在我杀死a.exe之后才开始的吗?
为什么会发生?
如何同时运行两者? (我需要做多线程吗?)
注意:我在Windows平台上
最佳答案
如果我们忽略异常,那么很容易同时运行多个程序:
#!/usr/bin/env python
import subprocess
# start all programs
processes = [subprocess.Popen(program) for program in ['a', 'b']]
# wait
for process in processes:
process.wait()
参见Python threading multiple bash subprocesses?
如果要停止先前启动的进程(如果任何程序无法启动):
#!/usr/bin/env python3
from contextlib import ExitStack
from subprocess import Popen
def kill(process):
if process.poll() is None: # still running
process.kill()
with ExitStack() as stack: # to clean up properly in case of exceptions
processes = []
for program in ['a', 'b']:
processes.append(stack.enter_context(Popen(program))) # start program
stack.callback(kill, processes[-1])
for process in processes:
process.wait()