【问题标题】:Python custom delimiter for read or readline用于读取或读取行的 Python 自定义分隔符
【发布时间】:2017-07-25 13:14:52
【问题描述】:

我正在与subprocess 交互,并尝试检测它何时准备好接受我的输入。我遇到的问题是 read 或 readline 函数依赖于行尾的 '\n' 分隔符,或者 EOF 来产生。由于这个subprocess 永远不会退出,因此文件中没有EOF 之类的对象。由于我要触发的关键字不包含该分隔符,因此 read 和 readline 函数永远不会产生。例如:

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

由于此过程永远不会退出,因此 read 或 read 行永远不会看到它需要让步的 EOF\n

有没有办法像对象一样读取这个文件并将自定义分隔符设置为input>

【问题讨论】:

  • 你能展示你的代码吗? (一个小例子)
  • 我们真的需要minimal reproducible example 来帮助您解决这个问题。
  • 一次读取输入的一个字符。

标签: python delimiter readline


【解决方案1】:

您可以实现自己的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 设置为 @987654324 @ 然后逐个字符读取输入。因此,对于您的示例,您需要做的就是:

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

【讨论】:

  • 谢谢!我很接近我对上述内容进行了粗略的实现,但它并没有点击让我使用 1 的 chunk_size
  • 好答案,好代码,糟糕的代码注释方式。如果某人不清楚while not handle.closed,那么他们为什么会理解“当我们的句柄打开时”?这几乎是一回事。评论应该解释“为什么”而不是“如何”。从代码中应该清楚“如何”,如果不是,那么它就是糟糕的代码。
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多