title: How do I ensure that a Python thread dies after its target function completes?
body: <p>I have a service that spawns threads. <br>
  The threads are started by providing a target function. <br>
  It would appear that the thread doesn't "die" when the function ends.  I know this because the thread makes some SSH connections with <a href="http://www.lag.net/paramiko/" rel="nofollow">Paramiko</a> (via <a href="http://fabfile.org" rel="nofollow">Fabric</a>), and if I do an <code>lsof</code> I see the SSH connections are still active after the function completes.<br>
  How can I make sure that a thread dies when its target function completes?</p>
  
  <p>Here is an example of what I am working with:</p>
  
  <pre><code>from time import sleep
  from threading import Thread
  from fabric.api import run, settings
  
  def thread_func(host):
      with settings(host_string=host):
          run('ls -lht /tmp')
  
  def spawn_thread(host):
      t = Thread(
          target=thread_func,
          args=(host,)
      )
      t.start()
  
  spawn_thread('node1.example.com')
  while True:
      sleep(1)
  </code></pre>
  
  <p>And if I run <code>sudo lsof | grep ssh</code> in another terminal while the above code is in its infinite loop I'll see the following, even after I <i>know</i> that the thread should not exist anymore:</p>
  
  <pre><code>python    6924      daharon    3u     IPv4             170520        0t0        TCP 10.1.1.173:47368-&gt;node1.example.com:ssh (ESTABLISHED)
  python    6924      daharon    5u     IPv4             170524        0t0        TCP 10.1.1.173:47369-&gt;node1.example.com:ssh (ESTABLISHED)
  python    6924 6930 daharon    3u     IPv4             170520        0t0        TCP 10.1.1.173:47368-&gt;node1.example.com:ssh (ESTABLISHED)
  python    6924 6930 daharon    5u     IPv4             170524        0t0        TCP 10.1.1.173:47369-&gt;node1.example.com:ssh (ESTABLISHED)
  python    6924 6932 daharon    3u     IPv4             170520        0t0        TCP 10.1.1.173:47368-&gt;node1.example.com:ssh (ESTABLISHED)
  python    6924 6932 daharon    5u     IPv4             170524        0t0        TCP 10.1.1.173:47369-&gt;node1.example.com:ssh (ESTABLISHED)
  </code></pre>