【发布时间】:2011-10-17 02:00:36
【问题描述】:
我正在尝试使用 Python 中的 subprocess 模块与以流方式读取标准输入并写入标准输出的进程进行通信。我想让子进程从产生输入的迭代器中读取行,然后从子进程中读取输出行。输入和输出线之间可能没有一一对应的关系。如何从返回字符串的任意迭代器中提供子进程?
这里有一些示例代码给出了一个简单的测试用例,以及我尝试过的一些方法由于某种原因不起作用:
#!/usr/bin/python
from subprocess import *
# A really big iterator
input_iterator = ("hello %s\n" % x for x in xrange(100000000))
# I thought that stdin could be any iterable, but it actually wants a
# filehandle, so this fails with an error.
subproc = Popen("cat", stdin=input_iterator, stdout=PIPE)
# This works, but it first sends *all* the input at once, then returns
# *all* the output as a string, rather than giving me an iterator over
# the output. This uses up all my memory, because the input is several
# hundred million lines.
subproc = Popen("cat", stdin=PIPE, stdout=PIPE)
output, error = subproc.communicate("".join(input_iterator))
output_lines = output.split("\n")
那么当我从迭代器的标准输出中逐行读取时,如何让我的子进程逐行读取呢?
【问题讨论】:
-
如何让脚本在后台运行?或者你只是不这样做? (我以为您来自 Q 的措辞“我正在尝试使用 Python 中的 subprocess 模块与读取标准输入并以流方式写入标准输出的进程进行通信。”
标签: python io subprocess