title: Why can't I handle a KeyboardInterrupt in python?
body: <p>I'm writing python 2.6.6 code on windows that looks like this:</p>
  
  <pre><code>try:
      dostuff()
  except KeyboardInterrupt:
      print "Interrupted!"
  except:
      print "Some other exception?"
  finally:
      print "cleaning up...."
      print "done."
  </code></pre>
  
  <p><code>dostuff()</code> is a function that loops forever, reading a line at a time from an input stream and acting on it. I want to be able to stop it and clean up when I hit ctrl-c.</p>
  
  <p>What's happening instead is that the code under <code>except KeyboardInterrupt:</code> isn't running at all. The only thing that gets printed is "cleaning up...", and then a traceback is printed that looks like this:</p>
  
  <pre><code>Traceback (most recent call last):
    File "filename.py", line 119, in &lt;module&gt;
      print 'cleaning up...'
  KeyboardInterrupt
  </code></pre>
  
  <p>So, exception handling code is NOT running, and the traceback claims that a KeyboardInterrupt occurred <em>during the finally clause</em>, which doesn't make sense because hitting ctrl-c is what caused that part to run in the first place! Even the generic <code>except:</code> clause isn't running.</p>
  
  <p><strong>EDIT:</strong> Based on the comments, I replaced the contents of the <code>try:</code> block with sys.stdin.read(). The problem still occurs exactly as described, with the first line of the <code>finally:</code> block running and then printing the same traceback.</p>
  
  <p><strong>EDIT #2:</strong>
  If I add pretty much anything after the read, the handler works. So, this fails:</p>
  
  <pre><code>try:
      sys.stdin.read()
  except KeyboardInterrupt:
      ...
  </code></pre>
  
  <p>But this works:</p>
  
  <pre><code>try:
      sys.stdin.read()
      print "Done reading."
  except KeyboardInterrupt:
      ...
  </code></pre>
  
  <p>Here's what's printed:</p>
  
  <pre><code>Done reading. Interrupted!
  cleaning up...
  done.
  </code></pre>
  
  <p>So, for some reason, the "Done reading." line is printed, even though the exception occurred on the previous line. That's not really a problem - obviously I have to be able to handle an exception anywhere inside the "try" block. However, the print doesn't work normally - it doesn't print a newline afterwards like it's supposed to! The "Interruped" is printed on the same line... with a space before it, for some reason...? Anyway, after that the code does what it's supposed to.</p>
  
  <p>It seems to me that this is a bug in handling an interrupt during a blocked system call.</p>