Python read 或 readline 的自定义分隔符

Python custom delimiter for read or readline

我正在与 subprocess 交互并尝试检测它何时准备好接受我的输入。我遇到的问题是读取或 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_size1然后逐个字符读取输入。因此,对于您的示例,您需要做的就是:

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 中捕获 > 之前的所有内容。您也可以在此版本中使用多个字符作为分隔符。