且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将大量数据写入标准输入

更新时间:2023-11-17 23:18:10

为了以可移植的方式避免死锁,请在单独的线程中写入孩子:

To avoid the deadlock in a portable way, write to the child in a separate thread:

#!/usr/bin/env python
from subprocess import Popen, PIPE
from threading import Thread

def pump_input(pipe, lines):
    with pipe:
        for line in lines:
            pipe.write(line)

p = Popen(path, stdin=PIPE, stdout=PIPE, bufsize=1)
Thread(target=pump_input, args=[p.stdin, lines]).start()
with p.stdout:
    for line in iter(p.stdout.readline, b''): # read output
        print line,
p.wait()

参见 Python:从 subprocess.communicate() 读取流输入