代码之家  ›  专栏  ›  技术社区  ›  dbr

重定向stdout时出现unicodeencodeerror[重复]

  •  21
  • dbr  · 技术社区  · 15 年前

    关于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)
    

    为什么会这样?我怎么修?

    1 回复  |  直到 15 年前
        1
  •  9
  •   Ignacio Vazquez-Abrams    15 年前

    不通向终端的管道没有编码,因此需要检查 sys.stdout.isatty() 并根据需要进行编码。