title: How to silence "sys.excepthook is missing" error?
body: <p>NB: I have not attempted to reproduce the problem described below under Windows, or with versions of Python other than 2.7.3.</p>
  
  <p>The most reliable way to elicit the problem in question is to pipe the output of the following test script through <code>:</code> (under <code>bash</code>):</p>
  
  <pre><code>try:
      for n in range(20):
          print n
  except:
      pass
  </code></pre>
  
  <p>I.e.:</p>
  
  <pre><code>% python testscript.py | :
  close failed in file object destructor:
  sys.excepthook is missing
  lost sys.stderr
  </code></pre>
  
  <p>My question is:</p>
  
  <blockquote>
    <p><em>How can I modify the test script above</em> to avoid the error message when the script is run as shown (under Unix/<code>bash</code>)?</p>
  </blockquote>
  
  <p>(As the test script shows, the error cannot be trapped with a <code>try-except</code>.)</p>
  
  <p>The example above is, admittedly, highly artificial, but I'm running into the same problem <em>sometimes</em> when the output of a script of mine is piped through some 3rd party software.</p>
  
  <p>The error message is certainly harmless, but it is disconcerting to end-users, so I would like to silence it.</p>
  
  <p>EDIT: The following script, which differs from the original one above only in that it redefines sys.excepthook, behaves exactly like the one given above.</p>
  
  <pre><code>import sys
  STDERR = sys.stderr
  def excepthook(*args):
      print &gt;&gt; STDERR, 'caught'
      print &gt;&gt; STDERR, args
  
  sys.excepthook = excepthook
  
  try:
      for n in range(20):
          print n
  except:
      pass
  </code></pre>