让 readline 在 FIFO 上阻塞
我创建了一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 readline 的文档,它返回空字符串当且仅如果您位于文件末尾。关闭与文件结束不同。仅当调用 .close() 时,文件对象才会关闭。当代码到达文件末尾时,readline() 不断返回空字符串。
如果你只使用文件对象作为迭代器,Python 将自动一次读取一行并在文件末尾停止。像这样:
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:
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.