获取读取行以阻塞FIFO [英] Getting readline to block on a FIFO

查看:97
本文介绍了获取读取行以阻塞FIFO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个fifo:

I create a fifo:

mkfifo tofetch

我运行以下python代码:

I run this python code:

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

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

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?

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

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.

推荐答案

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

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.

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

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

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

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.

这篇关于获取读取行以阻塞FIFO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆