重定向stdout时的UnicodeEncodeError

dbr*_*dbr 21 python unicode

我在Python中遇到有关Unicode的问题.我可以在常规终端中打印输出正常,但如果我重定向stdout到其他地方(或用subprocess模块捕获它),我得到一个UnicodeEncodeError:

$ cat example.py 
print u'Example: \u00F1'
$ python example.py 
Example: ñ
$ python example.py > /dev/null
Traceback (most recent call last):
  File "example.py", line 1, in <module>
    print u'Example: \u00F1'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 9: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

为什么是这样?我该如何解决?

Ign*_*ams 9

不通向终端的管道没有编码,因此sys.stdout.isatty()如果需要,您需要检查和编码.

  • @ eric.frederich或者在脚本开头使用它:`sys.stdout = codecs.getwriter("UTF-8")(sys.stdout)`,当然导入`codecs`和`sys`之后. (4认同)
  • 或者(甚至更好)只是总是编码. (3认同)
  • @eric,`print mystring.encode(encoding,'ignore')` (3认同)
  • 有没有一种简单的方法来"永远编码"? (2认同)