您可以實現自己的readlines
功能,並選擇分隔符自己:
def custom_readlines(handle, line_separator="\n", chunk_size=64):
buf = "" # storage buffer
while not handle.closed: # while our handle is open
data = handle.read(chunk_size) # read `chunk_size` sized data from the passed handle
if not data: # no more data...
break # break away...
buf += data # add the collected data to the internal buffer
if line_separator in buf: # we've encountered a separator
chunks = buf.split(line_separator)
buf = chunks.pop() # keep the last entry in our buffer
for chunk in chunks: # yield the rest
yield chunk + line_separator
if buf:
yield buf # return the last buffer if any
不幸的是,由於Python的默認緩衝策略,您將無法獲取數據的大片,如果不提供他們您打電話的過程,但您始終可以將chunk_size
設置爲1
,然後逐字讀取輸入字符。所以,你的榜樣,所有你需要做的是:
import subprocess
proc = subprocess.Popen(["your", "subprocess", "command"], stdout=subprocess.PIPE)
while chunk in custom_readlines(proc.stdout, ">", 1):
print(chunk)
# do whatever you want here...
它應該從你的子進程STDOUT捕捉一切達>
。您也可以在此版本中使用多個字符作爲分隔符。
你能展示你的代碼嗎? (一個小例子) –
我們確實需要一個[mcve]來幫助你解決這個問題。 –
一次讀取輸入的一個字符。 – Goyo