【问题标题】:Python chokes on non-ascii characters when output to a UNIX pipeline输出到 UNIX 管道时,Python 会阻塞非 ascii 字符
【发布时间】:2016-11-23 18:35:03
【问题描述】:

这是我的脚本的精简内容:

print u"w\xa0p"

将打印“w”字符,后跟一个不间断空格,然后将“p”打印到 TTY。然而,当这个脚本被传递到管道时,例如

python script.py | cat

(管道右边的确切命令并不重要,只要将python命令传递到UNIX管道上),python会报这种错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 1: ordinal not in range(128)

谁能解释为什么会发生这个错误,以及如何缓解它?显然有一个不同的编解码器,我想我们可以使用unidecode 包来以字符精度为代价来缓解这个问题;但我想知道如果输出管道正在使用中,我们是否可以强制 python 打印出 utf-8 字符。

【问题讨论】:

    标签: python unix pipe


    【解决方案1】:

    看看这个问题,你有同样的问题UnicodeDecodeError when redirecting to file

    您应该阅读EOL 的所有答案以了解问题,但如果您赶时间,这里是您需要使用的代码的重要部分:

    import codecs
    import locale
    import sys
    
    # Wrap sys.stdout into a StreamWriter to allow writing unicode.
    sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
    
    uni = u"w\xa0p"
    print uni
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-16
      • 2011-12-05
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 2016-08-09
      相关资源
      最近更新 更多