gpt4 book ai didi

用于读取或读取行的 Python 自定义分隔符

转载 作者:行者123 更新时间:2023-11-30 22:32:59 25 4
gpt4 key购买 nike

我正在与子进程进行交互,并尝试检测它何时准备好接受我的输入。我遇到的问题是 read 或 readline 函数依赖于行末尾的 '\n' 分隔符或 EOF 来产生。由于此子进程永远不会退出,因此文件类对象中没有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 中捕获 > 之前的所有内容。在此版本中,您还可以使用多个字符作为分隔符。

关于用于读取或读取行的 Python 自定义分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45304492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com