gpt4 book ai didi

Python 读取流

转载 作者:太空狗 更新时间:2023-10-29 17:06:47 25 4
gpt4 key购买 nike

我需要一种非常廉价的方法来读取 Python 中没有终止字符串(流)的缓冲区。这就是我所拥有的,但它浪费了 大量 CPU 时间和精力。因为它在不断地“尝试和捕捉”。我真的需要一种新方法。

这是我的代码的简化工作版本:

#! /usr/bin/env/ python
import fcntl, os, sys

if __name__ == "__main__":
f = open("/dev/urandom", "r")
fd = f.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

ready = False
line = ""
while True:
try:
char = f.read()
if char == '\r':
continue
elif char = '\n':
ready = True
else:
line += char
except:
continue
if ready:
print line

不要在终端中运行它。这只是为了说明。 “urandom”会破坏你的终端,因为它会吐出很多随机字符,终端模拟器无论如何都会解释这些字符(这会改变你当前的 shell 设置、标题等)。我正在从通过 USB 连接的 GPS 读取数据。

问题:这会尽可能使用 100% 的 CPU 使用率。我试过这个:

#! /usr/bin/env/ python
import fcntl, os, sys

if __name__ == "__main__":
f = open("/dev/urandom", "r")
fd = f.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

for line in f.readlines():
print line

但是,我得到 IOError: [Errno 11] Resource temporarily unavailable。我尝试使用 Popen 等等。我很茫然。有人可以提供解决方案吗(请解释一切,因为我本身不是专业人士)。另外,我应该指出,这是针对 Unix(尤其是 Linux,但它必须可移植到所有 Linux 版本)的。

最佳答案

您需要将缓冲模式设置为打开文件流时要读取的 block 的大小。来自 python 文档:

io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)

"buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer."

您还想在 while 循环中使用 readable() 方法,以避免不必要的资源消耗。

但是,我建议您使用缓冲流,例如io.BytesIOio.BufferedReader

更多信息在 docs .

关于Python 读取流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26127889/

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