gpt4 book ai didi

python - 让 readline 在 FIFO 上阻塞

转载 作者:太空狗 更新时间:2023-10-29 21:53:45 26 4
gpt4 key购买 nike

我创建了一个 fifo:

mkfifo tofetch

我运行这段 python 代码:

fetchlistfile = file("tofetch", "r")
while 1:
nextfetch = fetchlistfile.readline()
print nextfetch

正如我所希望的那样,它在 readline 上停滞了。我跑:

echo "test" > tofetch

而且我的程序不再停止。它读取该行,然后继续无限循环。为什么没有新数据时它不会再次停止?

我也尝试查看“not fetchlistfile.closed”,我不介意在每次写入后重新打开它,但 Python 认为 fifo 仍然打开。

最佳答案

根据 readline 的文档,当且仅当您位于文件末尾时,它才返回空字符串。关闭与文件结尾不同。文件对象只会在您调用 .close() 时关闭。当您的代码到达文件末尾时,readline() 会一直返回空字符串。

如果您只是将文件对象用作迭代器,Python 将自动一次读取一行并在文件末尾停止。像这样:

fetchlistfile = file("tofetch", "r")
for nextfetch in fetchlistfile:
print nextfetch

echo "test"> tofetch 命令打开命名管道,向其中写入“test”,然后关闭管道的末端。因为管道的写入端关闭,读取端看到文件结束。

关于python - 让 readline 在 FIFO 上阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2406365/

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