title: python loop a queue without while
body: <p>I'm now playing with multiprocessing and queue in Python 2.7 and try to print out 0 to 7 with variable p. When <code>while</code> is used as the commented codes shown in option 1, it works. However when the <code>for</code> and <code>iter()</code> are used as shown in option 2, 0 to 7 do print, yet the program never exits the loop and I have to exit manually. Any suggestions on how to modify the codes to have the loop exit normally after printing? With <code>iter()</code>, is there a way to set the <code>block=False</code> for the input arg <code>p.get</code>?</p>
  
  <pre><code>def try_queue():
      q = Queue()
      for i in range(10):
          q.put(i)
  
      p = Queue()
      for j in iter(q.get,8):
          p.put(j)
  
      # option 1, use while, works. 
      # while not p.empty():
      #   print(p.get()) 
  
      # option 2, use iter()
      for k in iter(p.get, None): # None is the sentinel here
          print(k)
  
  try_queue()
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/6cIom.png" rel="nofollow noreferrer">Result of option 1</a></p>
  
  <p><a href="https://i.stack.imgur.com/73JAr.png" rel="nofollow noreferrer">Result of option 2</a></p>