Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running two executable in parallel with os.system() in Python?

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

like image 676
ngub05 Avatar asked Oct 16 '25 09:10

ngub05


2 Answers

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()
like image 129
jfs Avatar answered Oct 18 '25 23:10

jfs


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',))
like image 20
Christian Avatar answered Oct 19 '25 00:10

Christian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!