Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting unicode strings via sys.stdout in Python
    primarykey
    data
    text
    <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>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload