Skip to main content
 首页 » 编程设计

python之并行运行子进程

2025年05月04日14freeliver54

我有一个 python 脚本,它必须调用某个应用程序 3 次。这些调用应该是并行的,因为它们需要数小时才能完成并且彼此不依赖。但是他们的脚本应该停止,直到所有脚本都完成,然后再做一些清理工作。

这是一些代码:

#do some stuff 
 
for work in worklist:   # these should run in parralel 
    output=open('test.txt','w') 
    subprocess.call(work,stdout=output,stderr=output) 
    output.close() 
 
# wait for subprocesses to finish 
 
# cleanup 

所以我基本上想并行运行这个命令,同时将它的输出捕获到一个文件中。完成所有实例后,我想继续执行脚本

请您参考如下方法:

subprocess.call() 正在阻塞。这意味着,每次调用都必须等待子进程完成才能继续。

您想要的是将参数传递给 subprocess.Popen 构造函数。这样,您的子进程将在没有阻塞的情况下启动。

稍后,您可以通过调用 Popen.communicate() 或 Popen.wait() 将这些子进程连接在一起。

child_processes = [] 
for work, filename in worklist: 
    with io.open(filename, mode='wb') as out: 
        p = subprocess.Popen(work, stdout=out, stderr=out) 
        child_processes.append(p)    # start this one, and immediately return to start another 
 
# now you can join them together 
for cp in child_processes: 
    cp.wait()                         # this will block on each child process until it exits 

附言您是否查看过有关 subprocess module 的 Python 文档? ?