擅长:python、mysql、java
<p>在这种情况下,Windows的行为有点复杂。您应该听取其他建议,并在内部对字符串使用unicode,并在输入期间进行解码。</p>
<p>对于您的问题,您需要打印编码字符串(只有您知道是哪种编码!)在stdout重定向的情况下,但是在简单屏幕输出的情况下,您必须打印unicode字符串(python或windows控制台处理到正确编码的转换)。</p>
<p>我建议你的脚本结构如下:</p>
<pre><code># -*- coding: utf-8 -*-
import sys, codecs
# set up output encoding
if not sys.stdout.isatty():
# here you can set encoding for your 'out.txt' file
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
# next, you will print all strings in unicode
print u"Unicode string ěščřžý"
</code></pre>
<p>更新:另请参见其他类似问题:<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>