如果需要纯Python解决方案,则需要将读取器或写入器放在单独的线程中。该threading
软件包是一种轻量级的方法,可以方便地访问常见对象并且不会造成混乱。
import subprocess
import threading
import sys
proc = subprocess.Popen(['cat','-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
def writer():
for i in range(100000):
proc.stdin.write(b'%d\n' % i)
proc.stdin.close()
thread = threading.Thread(target=writer)
thread.start()
for line in proc.stdout:
sys.stdout.write(line.decode())
thread.join()
proc.wait()
看到subprocess
现代化的模块以支持流和协程可能会很整洁,这将允许混合使用Python片段和Shell片段的管道更优雅地构建。