【问题标题】:Wait the end of subprocesses with multiple parallel jobs等待具有多个并行作业的子进程结束
【发布时间】:2010-07-07 10:55:31
【问题描述】:

我正在从 python 并行运行一些子进程。我想等到每个子流程都完成。我正在做一个非优雅的解决方案:

runcodes = ["script1.C", "script2.C"]
ps = []
for script in runcodes:
  args = ["root", "-l", "-q", script]
  p = subprocess.Popen(args)
  ps.append(p)
while True:
  ps_status = [p.poll() for p in ps]
  if all([x is not None for x in ps_status]):
    break

有没有可以处理多个子进程的类?问题是wait 方法阻塞了我的程序。

更新:我想显示计算过程中的进度:类似于“4/7 subprocess finished...”

如果你好奇root编译c++脚本并执行它。

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    如果您的平台不是 Windows,您可能会选择子进程的标准输出管道。然后,您的应用将被阻止,直到:

    • 其中一个已注册的文件描述符有一个 I/O 事件(在这种情况下,我们感兴趣的是子进程的 stdout 管道上的挂断)
    • 轮询超时

    在 Linux 2.6.xx 中使用 epoll 的非充实示例:

    import subprocess
    import select
    
    poller = select.epoll()
    subprocs = {} #map stdout pipe's file descriptor to the Popen object
    
    #spawn some processes
    for i in xrange(5):
        subproc = subprocess.Popen(["mylongrunningproc"], stdout=subprocess.PIPE)
        subprocs[subproc.stdout.fileno()] = subproc
        poller.register(subproc.stdout, select.EPOLLHUP)
    
    #loop that polls until completion
    while True:
        for fd, flags in poller.poll(timeout=1): #never more than a second without a UI update
            done_proc = subprocs[fd]
            poller.unregister(fd)
            print "this proc is done! blah blah blah"
            ...  #do whatever
        #print a reassuring spinning progress widget
        ...
        #don't forget to break when all are done
    

    【讨论】:

    • 这很好!有没有办法让subproc.stdout 在mylongrunningproc 运行时打印到终端?
    • 首先想到的是还要为输入事件注册标准输出管道 - poller.register(subproc.stdout, select.EPOLLHUP | select.EPOLLIN)。然后你可以做if flags & select.EPOLLIN: print done_proc.stdout.readline()。如果输出不是行分隔的,您必须小心无限期地阻塞。在linux中我认为你可以通过使用fcntl将stdout管道设置为非阻塞,然后用errno=EAGAIN捕获IOError来解决这个问题。前 - fcntl.fcntl(subproc.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
    • 管道非阻塞读取的参考链接 - (gossamer-threads.com/lists/python/dev/658205)
    • 如果解决方案基于 select 系统调用,则可能更好的更高级别抽象是最终基于此的 asyncio。我将为此创建另一个答案。
    【解决方案2】:

    怎么样

    导入操作系统,子进程 运行代码 = ["script1.C", "script2.C"] ps = {} 对于运行代码中的脚本: args = [“根”,“-l”,“-q”,脚本] p = subprocess.Popen(args) ps[p.pid] = p print "等待 %d 个进程..." % len(ps) 而ps: pid,状态 = os.wait() 如果 ps 中的 pid: 德尔 ps[pid] print "等待 %d 个进程..." % len(ps)

    【讨论】:

    • 注意:os.wait() 需要linux
    【解决方案3】:

    你可以这样做:

    runcodes = ["script1.C", "script2.C"]
    
    ps = []
    for script in runcodes:
        args = ["root", "-l", "-q", script]
        p = subprocess.Popen(args)
        ps.append(p)
    
    for p in ps:
        p.wait()
    

    这些进程将并行运行,最后您将等待所有进程。

    【讨论】:

    • 是的,问题是我不能在执行过程中写#process finished,因为假设第一个子进程非常慢,p 等于第一个ps,python 正在等待并冻结直到第一次完成; python不能写除了第一个子进程之外的所有子进程都完成了。
    • 如果我想等待第一个完成过程,什么时候杀死另一个?
    【解决方案4】:

    我认为答案不在于 python 代码或语言特性,而在于系统功能,请考虑以下解决方案:

    runcodes = ["script1.C", "script2.C"]
    
    Args = []
    for script in runcodes:
        Args += " ".join(["root", "-l", "-q", script])
    
    
    P = subprocess.Popen(" & ".join(Args))
    P.wait()
    

    【讨论】:

    • 依赖系统能力?不太便携
    • 是的,这里不是便携式的,但我确实认为需要两行才能做到这一点。对不起,我是 linux 用户。
    • 检测 os 系统然后将 & 更改为 winodows 等效项。
    【解决方案5】:

    这个答案与this answer 相关,并在下面使用了一个类似的机制(基于select 系统调用),称为asyncio。 你可以阅读更多关于asynciohere的信息。

    当您的进程受 IO 限制时,Asyncio 很好。您的进程似乎是 IO 绑定的,至少在程序的这一部分中,大部分时间都在等待外部脚本完成并且只在它们结束时打印一条消息。

    下面的代码应该适合你(也许有一些小的调整):

    import asyncio
    
    # The scripts you want to run concurrently
    runcodes = ["script1.C", "script2.C"]
    
    # An awaitable coroutine that calls your script
    # and waits (non-blocking) until the script is done 
    # to print a message
    async def run_script(script):
        # You will need to adjust the arguments of create_subprocess_exec here
        # according to your needs
        p = await asyncio.create_subprocess_exec(script)
        await p.wait()
        print("Script", script, "is done")
    
    # You create concurrent tasks for each script
    # they will start in parallel as soon as they are
    # created
    async def main():
        tasks = []
        for script in runcodes:
            tasks.append(asyncio.create_task(run_script(script)))
    
        # You wait until all the tasks are done before 
        # continuing your program
        for task in tasks:
            await task
    
    if __name__ == "__main__":
        asyncio.run(main())
    

    一些详细的解释。

    Asyncio 允许您使用单个线程执行并发任务,方法是交替各种异步任务并在所有异步任务都被阻塞时等待。

    函数run_script 是异步的,将使用与subprocess.Popen 类似的机制调用您的脚本。这里的区别在于返回的对象是可等待的,这意味着你可以在等待函数被阻塞时跳转到别的东西。

    您可以通过asynciohere 阅读有关子流程管理的更多信息。您会注意到子进程的管理与“正常”的 Python 子进程非常相似。 Popen 的论点也类似。

    请注意,这与线程不同。事实上,这个程序是单线程的。不要将 asyncio 与多线程混淆。它们是同时运行任务的两种不同方法(各有利弊)。

    主函数将创建多个任务,每个脚本对应一个您要运行并等待它们的任务。

    重要的是这个await 不会阻塞,同时它也不会进行实时轮询。它会一直休眠,直到任何任务都准备好。一旦任务准备就绪,执行将返回到该任务,该任务可以打印有关您的消息的语句。

    不过,在所有等待的任务完成之前,程序不会退出主函数。它将停留在 asyncio.run 生成的等待函数循环中,直到一切完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 2022-12-18
      相关资源
      最近更新 更多