title: Writing unicode strings via sys.stdout in Python
body: <p>Assume for a moment that one cannot use <code>print</code> (and thus enjoy the benefit of automatic encoding detection). So that leaves us with <code>sys.stdout</code>. However, <code>sys.stdout</code> is so dumb as to <a href="http://bugs.python.org/issue4947" rel="noreferrer">not do any sensible encoding</a>.</p>
  
  <p>Now one reads the Python wiki page <a href="http://wiki.python.org/moin/PrintFails" rel="noreferrer">PrintFails</a> and goes to try out the following code:</p>
  
  <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \
    sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout);
  </code></pre>
  
  <p>However this too does not work (at least on Mac). Too see why:</p>
  
  <pre><code>&gt;&gt;&gt; import locale
  &gt;&gt;&gt; locale.getpreferredencoding()
  'mac-roman'
  &gt;&gt;&gt; sys.stdout.encoding
  'UTF-8'
  </code></pre>
  
  <p>(UTF-8 is what one's terminal understands).</p>
  
  <p>So one changes the above code to:</p>
  
  <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \
    sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout);
  </code></pre>
  
  <p>And now unicode strings are properly sent to <code>sys.stdout</code> and hence printed properly on the terminal (<code>sys.stdout</code> is attached the terminal).</p>
  
  <p>Is this the correct way to write unicode strings in <code>sys.stdout</code> or should I be doing something else?</p>
  
  <p><strong>EDIT</strong>: at times--say, when piping the output to <code>less</code>--<code>sys.stdout.encoding</code> will be <code>None</code>. in this case, the above code will fail.</p>