2017-07-25 201 views
0

我有subprocess交互和嘗試檢測何時準備好我的輸入。即我遇到的問題是,讀或readline功能依賴於「\ N」在該行或EOF,得到的末端分隔符。由於這subprocess永遠不會退出,有喜歡的對象的文件中沒有EOF。因爲我想要觸發關閉關鍵字不包含分隔符的讀取和readline功能永不屈服。例如:讀或Python的readline的自定義分隔符

'Doing something\n' 
'Doing something else\n' 
'input>' 

由於這個過程不退出,讀取或讀線從未看到EOF\n,它需要得到。

有沒有辦法像對象一樣讀取此文件並將自定義分隔符設置爲input>

+0

你能展示你的代碼嗎? (一個小例子) –

+0

我們確實需要一個[mcve]來幫助你解決這個問題。 –

+0

一次讀取輸入的一個字符。 – Goyo

回答

0

您可以實現自己的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捕捉一切達>。您也可以在此版本中使用多個字符作爲分隔符。

+0

謝謝!我很接近,我有一個粗略的實現上述,但它沒有點擊我使用chunk_size爲1 – wdoler

相關問題