您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用subprocess.Popen时将大量数据通过管道传输到stdin

使用subprocess.Popen时将大量数据通过管道传输到stdin

如果需要纯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片段的管道更优雅地构建。

其他 2022/1/1 18:31:07 有484人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶