I want to use os.mkfifo for easy communication between programs. I have a problem reading from fifo in a loop.
Consider this toy example where I have a reader and writer working with fifo. I want to be able to run the reader in a loop to read everything that goes into fifo.
# reader.py import os import atexit FIFO = 'json.fifo' @atexit.register def cleanup(): try: os.unlink(FIFO) except: pass def main(): os.mkfifo(FIFO) with open(FIFO) as fifo: # for line in fifo: # closes after single reading # for line in fifo.readlines(): # closes after single reading while True: line = fifo.read() # will return empty lines (non-blocking) print repr(line) main()
And the writer:
# writer.py import sys FIFO = 'json.fifo' def main(): with open(FIFO, 'a') as fifo: fifo.write(sys.argv[1]) main()
If I run python reader.py and later python writer.py foo , "foo" will be printed, but fifo will close and the reader will exit (or start inside the while ). I want the reader to stay in the loop, so I can write to the screenwriter many times.
Edit
I use this snippet to solve the problem:
def read_fifo(filename): while True: with open(filename) as fifo: yield fifo.read()
but maybe there is a more accurate way to handle this, instead of reopening the file ...
Similar
- Getting readline to lock in FIFO
python mkfifo
Jakub M.
source share