python - 并行运行子进程

标签 python subprocess

我有一个 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 文档? ?

关于python - 并行运行子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23818569/

相关文章:

python - 为什么 psycopg2 对我这么慢?

Python Popen 写入 stdin 在线程中时不起作用

go - golang程序退出后如何保持子进程运行?

Python Popen.subprocess 退出状态0,但程序在子进程成功完成后立即退出

python - 在 Python Spark 中查看 RDD 内容?

python - Python 优先级队列中的 A* 搜索

python - 为什么 Authenticate 在 django 中返回 None

python - 以编程方式将图片导入 Apple Photos 并修改 Exif 数据

python - 如何使用可读的非阻塞输出管道在 linux 上的 python 中启动 node.js 子进程

python - 使用 pid 轮询子进程