如何从Python同时调用带参数的多个.exe程序?
Hey there! Let's break down how to solve your problem—launching multiple executables at once, including one that needs 5 arguments, while keeping that familiar command-line window output like os.system gives you.
First: Passing Arguments with subprocess
The key thing to know is that subprocess.run (and subprocess.Popen, which we'll use for parallel execution) works best when you pass the command and its arguments as a list of strings, not a single string. For your 5-argument executable, that looks like this:
import subprocess # This runs process.exe with 5 arguments, just like your os.system call subprocess.run(["process.exe", "arg1", "arg2", "arg3", "arg4", "arg5"])
If you want the command-line window to pop up (just like os.system), add the creationflags parameter to spawn a new console:
subprocess.run( ["process.exe", "arg1", "arg2", "arg3", "arg4", "arg5"], creationflags=subprocess.CREATE_NEW_CONSOLE )
Second: Launching Multiple Processes Simultaneously
The problem with subprocess.run is that it blocks your Python script until the executable finishes—so you can't run multiple at once. Instead, use subprocess.Popen—it starts the process and immediately returns control to your script, letting you launch others right away.
Here's a complete example that launches three executables in parallel (one with arguments, two without), each in their own command-line window:
import subprocess # Launch the executable with 5 arguments in a new console proc_with_args = subprocess.Popen( ["process.exe", "arg1", "arg2", "arg3", "arg4", "arg5"], creationflags=subprocess.CREATE_NEW_CONSOLE ) # Launch other executables simultaneously proc1 = subprocess.Popen(["another_process.exe"], creationflags=subprocess.CREATE_NEW_CONSOLE) proc2 = subprocess.Popen(["third_process.exe"], creationflags=subprocess.CREATE_NEW_CONSOLE) # Optional: Wait for all processes to finish before your script exits proc_with_args.wait() proc1.wait() proc2.wait()
Why This Works
Popenis non-blocking: Unlikeos.systemorsubprocess.run, it doesn't wait for one process to finish before starting the next—so all your executables run at the same time.- List-style arguments: This avoids common issues with spaces in file paths or arguments, and is the recommended way to use
subprocess(safer than passing a single string withshell=True). CREATE_NEW_CONSOLE: This flag ensures each executable gets its own command-line window, just likeos.systemdoes, so you can see their stdout/stderr output in real time.
内容的提问来源于stack exchange,提问作者TeaPack




