7

我创建了一个先进先出:

mkfifo tofetch

我运行这个 python 代码:

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

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

echo "test" > tofetch

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

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

4

1 回答 1

4

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.

于 2010-03-09T03:22:44.007 回答