title: Stdout encoding in python
body: <p>Is there a good reason why I shouldn't start <strong>all</strong> my python programs with this? Is there something special lost when doing exec like this?</p>
  
  <pre><code>#!/usr/bin/python
  import os, sys
  if sys.stdout.encoding == None:
      os.putenv("PYTHONIOENCODING",'UTF-8')
      os.execv(sys.executable,['python']+sys.argv)
  print sys.stdout.encoding
  </code></pre>
  
  <p>There are <a href="https://stackoverflow.com/search?q=PYTHONIOENCODING">60 questions about PYTHONIOENCODING</a> so I guess it's a common problem, but in case you don't know, this is done because when <code>sys.stdout.encoding == None</code> then you can only print ascii chars, so e.g. <code>print "åäö"</code> will throw an exception..</p>
  
  <p><strong>EDIT</strong> This happens to me when stdout is a pipe; <code>python encoding.py|cat</code> will set encoding to None</p>
  
  <p>Another solution is to change the <a href="https://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python?rq=1#1169209">codec of stdout</a> <code>sys.stdout = codecs.getwriter('utf8')(sys.stdout)</code> which I'm guessing is the correct answer dispite the comments on that question.</p>