让 readline 在 FIFO 上阻塞

发布于 2024-08-24 13:31:54 字数 438 浏览 7 评论 0原文

我创建了一个 fifo:

mkfifo tofetch

我运行这个 python 代码:

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

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

echo "test" > tofetch

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

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

I create a fifo:

mkfifo tofetch

I run this python code:

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

It stalls on readline, as I would hope. I run:

echo "test" > tofetch

And my program doesn't stall anymore. It reads the line, and then continues looping forever. Why won't it stall again when there's no new data?

I also tried looking on "not fetchlistfile.closed", I wouldn't mind reopening it after every write, but Python thinks the fifo is still open.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

把回忆走一遍 2024-08-31 13:31:54

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

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

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

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

According to the documentation for readline, it returns the empty string if and only if you're at end-of-file. Closed isn't the same as end-of-file. The file object will only be closed when you call .close(). When your code reaches the end of the file, readline() keeps returning the empty string.

If you just use the file object as an iterator, Python will automatically read a line at a time and stop at end-of-file. Like this:

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

The echo "test" > tofetch command opens the named pipe, writes "test" to it, and closes it's end of the pipe. Because the writing end of the pipe is closed, the reading end sees end-of-file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文