Skip to main content
 首页 » 编程设计

Python:使用子进程在没有死锁的情况下流式传输数据

2025年05月04日45zhengyun_ustc

我正在编写一个小脚本来随机播放大量数据。它是这样的:

outproc = None 
for input in input_files: 
    p = Popen('process_input "%s" | more_input_processing' %(input, ), 
              shell=True, stdout=PIPE) 
    for line in p.stdout.xreadlines(): 
        if linecount % 1000000 == 0: 
            outfile = "output%03d" %(linecount // 1000000, ) 
            if outproc: 
                outproc.stdin.close() 
                result = outproc.wait() # <-- deadlock here 
                assert result == 0, "outproc exited with %s" %(result, ) 
            outproc = Popen('handle_output "%s"' %(outfile, ), 
                            shell=True, stdin=PIPE) 
        linecount += 1 
        outproc.stdin.write(line) 
    p.stdout.close() 
    result = p.wait() 
    assert result == 0, "p exited with %s" %(result, ) 

不过,正如文档警告的那样,当我尝试等待 outproc 时遇到了死锁(请参阅评论)。

文档提出的“解决方案”是使用.communicate()……但是这样做会涉及在刷新之前将所有输入读入内存,这是不可取的。

那么,如何在没有死锁的情况下在子进程之间传输数据?

请您参考如下方法:

您没有在子进程实际读取的管道上使用 close,因此它不会收到 SIGPIPE 或任何导致其退出的信息。当你有足够的数据时,只需终止进程。或者,通过管道传输输入和输出,并使用 select 来了解何时应该读取或写入。