title: fifo - reading in a loop
body: <p>I want to use <a href="http://docs.python.org/2/library/os.html#os.mkfifo" rel="noreferrer">os.mkfifo</a> for simple communication between programs. I have a problem with reading from the fifo in a loop.</p>
  
  <p>Consider this toy example, where I have a reader and a writer working with the fifo. I want to be able to run the reader in a loop to read everything that enters the fifo.</p>
  
  <pre><code># 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()
  </code></pre>
  
  <p>And the writer:</p>
  
  <pre><code># writer.py
  import sys
  
  FIFO = 'json.fifo'
  
  
  def main():
      with open(FIFO, 'a') as fifo:
          fifo.write(sys.argv[1])
  
  main()
  </code></pre>
  
  <p>If I run <code>python reader.py</code> and later <code>python writer.py foo</code>, "foo" will be printed but the fifo will be closed and the reader will exit (or spin inside the <code>while</code> loop). I want reader to stay in the loop, so I can execute the writer many times.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I use this snippet to handle the issue:</p>
  
  <pre><code>def read_fifo(filename):
      while True:
          with open(filename) as fifo:
              yield fifo.read()
  </code></pre>
  
  <p>but maybe there is some neater way to handle it, instead of repetitively opening the file...</p>
  
  <p><strong>Related</strong></p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/2406365/getting-readline-to-block-on-a-fifo">Getting readline to block on a FIFO</a></li>
  </ul>