tags:

views:

159

answers:

1

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.

+2  A: 

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.

Daniel Stutzbach