我試圖使用subprocess
模塊在Python有一個過程,讀取標準輸入並以流方式寫到標準輸出進行通信。我想讓子進程從產生輸入的迭代器中讀取行,然後從子進程讀取輸出行。輸入和輸出線之間可能沒有一對一的對應關係。我如何從一個返回字符串的任意迭代器中提供一個子進程?如何從Python迭代器提供子進程的標準輸入?
下面是一些示例代碼,給出了一個簡單的測試案例,以及一些方法我都試過,由於某種原因或其他不工作:
#!/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")
所以,我怎麼能有我的子進程從讀迭代器一行一行,而我從它的標準輸出逐行讀取?
如果用戶在子進程中使用'exit()',則會引發'SystemExit'。應該改用['os._exit(0)'](https://docs.python.org/2/library/os.html#os._exit) – hakanc
[使用'Thread()'而不是'os.fork ()'](http://stackoverflow.com/a/32331150/4279)的可移植性和避免各種難以調試的問題。下面是'os.fork()'可能出現的問題的一個例子:[標準庫中的鎖應該在fork上清理](http://bugs.python.org/issue6721) – jfs