<p>我看到了三种解决方案:</p>
<ol>
<li><p>更改输出编码,使其始终输出UTF-8。请参见例如<a href="https://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python">Setting the correct encoding when piping stdout in Python</a>,但我无法使这些示例起作用。</p></li>
<li><p>下面的示例代码使输出知道目标字符集。</p>
<pre><code># -*- coding: utf-8 -*-
import sys
print sys.stdout.encoding
print u"Stöcker".encode(sys.stdout.encoding, errors='replace')
print u"Стоескер".encode(sys.stdout.encoding, errors='replace')
</code></pre>
<p>这个例子用问号正确地替换了我名字中任何不可打印的字符。</p>
<p>如果您创建了一个定制的打印函数,例如<code>myprint</code>,使用该机制正确地编码输出,您可以在任何需要的地方用<code>myprint</code>替换打印,而不必使整个代码看起来很难看。</p></li>
<li><p>在软件开始时全局重置输出编码:</p>
<p>页面<a href="http://www.macfreek.nl/memory/Encoding_of_Python_stdout" rel="noreferrer">http://www.macfreek.nl/memory/Encoding_of_Python_stdout</a>很好地总结了如何更改输出编码。特别是“StreamWriter包装Stdout”一节很有意思。实际上,它说要像这样更改I/O编码函数:</p>
<p>在Python 2中:</p>
<pre><code>if sys.stdout.encoding != 'cp850':
sys.stdout = codecs.getwriter('cp850')(sys.stdout, 'strict')
if sys.stderr.encoding != 'cp850':
sys.stderr = codecs.getwriter('cp850')(sys.stderr, 'strict')
</code></pre>
<p>在Python 3中:</p>
<pre><code>if sys.stdout.encoding != 'cp850':
sys.stdout = codecs.getwriter('cp850')(sys.stdout.buffer, 'strict')
if sys.stderr.encoding != 'cp850':
sys.stderr = codecs.getwriter('cp850')(sys.stderr.buffer, 'strict')
</code></pre>
<p>如果在CGI输出HTML中使用,则可以用“xmlcharrefreplace”替换“strict”,以获取不可打印字符的HTML编码标记。</p>
<p>请随意修改方法,设置不同的编码。。。。请注意,输出非指定数据仍然不起作用。因此,任何数据、输入、文本都必须能够正确地转换为unicode:</p>
<pre><code># -*- coding: utf-8 -*-
import sys
import codecs
sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
print u"Stöcker" # works
print "Stöcker".decode("utf-8") # works
print "Stöcker" # fails
</code></pre></li>
</ol>