TeaPack
TeaPack

Reputation: 51

Call multiple .exe from Python

I have a problem where I want to call multiple .exe files from Python at once and one .exe has like 5 arguments. How can I call it? I tried os.system("process.exe arg1 arg2 arg3 arg4") which works but it can only launch one process at time and I also tried subprocess.run, however while it can call process like subprocess.run("process.exe") I can't seem to find solution how to send arguments like subprocess.run("process.exe arg1 arg2 arg3"). I need it to also open commandline as stdout which os.system command can do.

Upvotes: 1

Views: 495

Answers (1)

Lipen
Lipen

Reputation: 85

If you want to spawn multiple processes simultaneously ("asynchronously", "in parallel"), use

p = subprocess.Popen("<command> <args>", shell=True, stdout=subprocess.PIPE)

which instantly returns the Popen instance (object representing the spawned process).

shell=True allows you to pass the command as a "simple string" (e.g. "myprog arg1 arg2"). Without shell=True you must pass the list of arguments, including the name of a program as a first arg (e.g. ["myprog", "arg1", "arg2"]).

stdout=PIPE ensures stdout capturing in a pipe (a file-like object in Python terms), which may be accessed via p.stdout. Use can read the output of your program via p.stdout.read().decode(), but note that this call is blocking, i.e. it awaits the program to stop, so in your case make sure that you have spawned all necessary processes before reading their outputs.

In order to await the program without reading its output, use p.wait().

More information in Python docs: subprocess.

Upvotes: 2

Related Questions