title: Understanding Python daemon threads
body: <p>I've obviously misunderstood something fundamental about a Python Thread object's daemon attribute.</p>
  
  <p>Consider the following:</p>
  
  <pre><code>daemonic.py
  
  import sys, threading, time
  
  class TestThread(threading.Thread):
      def __init__(self, daemon):
          threading.Thread.__init__(self)
          self.daemon = daemon
  
      def run(self):
          x = 0
          while 1:
              if self.daemon:
                  print "Daemon :: %s" % x
              else:
                  print "Non-Daemon :: %s" % x
              x += 1
              time.sleep(1)
  
  if __name__ == "__main__":
      print "__main__ start"
      if sys.argv[1] == "daemonic":
          thread = TestThread(True)
      else:
          thread = TestThread(False)
      thread.start()
      time.sleep(5)
      print "__main__ stop"
  </code></pre>
  
  <p>From the python docs: </p>
  
  <blockquote>
    <p>The entire Python program exits when
    no alive non-daemon threads are left.</p>
  </blockquote>
  
  <p>So if I run with TestThread as a daemon, I would expect it to exit once the main thread has completed.  But this doesn't happen:</p>
  
  <pre><code>&gt; python daemonic.py daemonic
  __main__ start
  Daemon :: 0
  Daemon :: 1
  Daemon :: 2
  Daemon :: 3
  Daemon :: 4
  __main__ stop
  Daemon :: 5
  Daemon :: 6
  ^C
  </code></pre>
  
  <p>What don't I get?</p>
  
  <hr>
  
  <p>As guessed by Justin and Brent, I was running with Python 2.5.  Have just got home and tried out on my own machine running 2.7, and everything works fine.  Thanks for your helps!</p>