【问题标题】:Python default character encoding handlingPython 默认字符编码处理
【发布时间】:2017-01-13 11:05:14
【问题描述】:

我看过几篇与此相关的帖子,但没有明确的答案。假设我想在仅支持 ASCII 的终端中打印字符串 s=u'\xe9\xe1'(例如,LC_ALL=C; python3)。有没有办法将以下配置为默认行为:

import sys
s = u'\xe9\xe1'
s = s.encode(sys.stdout.encoding, 'replace').decode(sys.stdout.encoding)
print(s)

即,我希望字符串打印一些东西——甚至是垃圾——而不是引发异常 (UnicodeEncodeError)。我正在使用python3.5。

我想避免为我所有可能包含 UTF-8 的字符串编写此代码。

【问题讨论】:

    标签: python character-encoding utf


    【解决方案1】:

    您可以做以下三件事之一:

    • 使用PYTHONIOENCODING environment variable 调整stdoutstderr 的错误处理程序:

      export PYTHONIOENCODING=:replace
      

      注意:;我没有指定编解码器,只指定了错误处理程序。

    • 替换stdoutTextIOWrapper,设置不同的错误处理程序:

      import sys
      import io
      
      sys.stdout = io.TextIOWrapper(
          sys.stdout.buffer, encoding=sys.stdout.encoding, 
          errors='replace',
          line_buffering=sys.stdout.line_buffering)
      
    • sys.stdout.buffer 周围创建一个单独的TextIOWrapper 实例,并在打印时将其作为file 参数传入:

      import sys
      import io
      
      replacing_stdout = io.TextIOWrapper(
          sys.stdout.buffer, encoding=sys.stdout.encoding, 
          errors='replace',
          line_buffering=sys.stdout.line_buffering)
      
      print(s, file=replacing_stdout)
      

    【讨论】:

    • 这正是我想要的——非常感谢! (我选择了选项 2)
    猜你喜欢
    • 2018-10-04
    • 2011-07-08
    • 2011-07-27
    • 1970-01-01
    • 2014-12-05
    • 2011-03-22
    • 2010-12-28
    • 2019-04-03
    • 2016-07-18
    相关资源
    最近更新 更多