1

I am using subprocess.Popen() to run processes and wait for them to finish before executing other things. For a single process I wrote my code in this general form:

process = subprocess.pOpen(['command', 'options...', '1> output.txt'])
process.wait()

more code...

and it worked just fine. The script waited for the process to output the results to output.txt before moving on to 'more code...'

However, I'm not sure what to do in order to run several concurrent processes, and wait for all of them to be done in order to move on to the rest of the code. Without the logic for waiting, my code generally looks like this:

for i in range(0, n_streams):
    os.system("start /b command [options] 1> output{0}.txt".format(i))

and it works fine; each process writes output to a text file and they run at the same time as I'd like. I just can't figure out how to make the program wait for all of them to have written to a text file before moving on.

I keep thinking all I need to do is replace os.system() with pOpen() and use wait() as I did for above for a single process, but this would just cause the instances of the process to run sequentially.

To reiterate my question: how can I run many instances of a process at the same time, and wait until all instances have finished (written to their respective output file) before moving on?

4

2 回答 2

0

只需存储所有已启动的进程,然后等待每个进程:

# Start and store all of your processes
processes = []
for i in range(0, n_streams):
    processes.append(subprocess.Popen(['command', 'options...', '1> output.txt']))

# Wait for all of them to complete
for proc in processes:
    proc.wait()
于 2014-02-15T00:42:28.820 回答
0

使用subprocess.Popen.returncode您可以检查子进程是否结束。

于 2013-03-25T19:36:56.230 回答