簡體   English   中英

讀取或讀取線的Python自定義分隔符

[英]Python custom delimiter for read or readline

我正在與subprocess交互並嘗試檢測它何時准備好輸入。 我遇到的問題是read或readline函數依賴於行尾的'\\ n'分隔符,或者產生EOF。 由於此subprocess永不退出,因此文件中沒有EOF ,如對象。 由於我想要觸發的關鍵字不包含該分隔符,因此read和readline函數永遠不會產生。 例如:

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

由於此過程永遠不會退出,因此讀取或讀取行永遠不會看到它需要產生的EOF\\n

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

您可以實現自己的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...

它應該抓住一切都交給>從你的子進程標准輸出。 您還可以在此版本中使用多個字符作為分隔符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM