I wish to run two executable a.exe and b.exe in parallel, invoked one after another.
When I tried,
os.system('a.exe')
#some code
os.system('b.exe')
b.exe is getting started only after I killed a.exe? Why does it happen? How can I run both simultaneously? (Do I need to do multithreading?) Note: I'm in Windows platform
If we ignore exceptions then it is simple to run several programs concurrently:
#!/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()
See Python threading multiple bash subprocesses?
If you want to stop previously started processes if any of the programs fails to start:
#!/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()
Try running each one as a separate thread:
import thread
thread.start_new_thread(os.system, ('a.exe',))
thread.start_new_thread(os.system, ('b.exe',))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With