Python3 和编码 : different on linux and on OSX?

标签 python unicode encoding python-3.x decode

这个字符串:

line = '\tlong_plugin_output=\x88\\\\\x97\xe5\xff\x7f\\n'

.. 打印时,在我的 Macbook Pro 上产生以下输出:

>>> line = '\tlong_plugin_output=\x88\\\\\x97\xe5\xff\x7f\\n'

>>> line
'\tlong_plugin_output=\x88\\\\\x97åÿ\x7f\\n'

>>> print(line)
    long_plugin_output=\\åÿ\n

.. 但是它在我的 ubuntu 服务器上产生了这个错误:

>>> line = '\tlong_plugin_output=\x88\\\\\x97\xe5\xff\x7f\\n'

>>> line
'\tlong_plugin_output=\x88\\\\\x97\xe5\xff\x7f\\n'

>>> print(line)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\x88' in position 20: ordinal not in range(128)

我在 macbook 上运行的 python 版本:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 13 2013, 13:52:24) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

$ uname -a Darwin MacBook-Pro.local 11.4.2 Darwin Kernel Version 11.4.2: Thu Aug 23 16:25:48 PDT 2012; root:xnu-1699.32.7~1/RELEASE_X86_64 x86_64

我在我的 Ubuntu 服务器上运行的 python 版本:

Python 3.2.3 (default, Sep 25 2013, 18:25:56) [GCC 4.6.3] on linux2

$ uname -a Linux net.local.net 3.2.2 #3 SMP Thu Jan 26 20:18:37 UTC 2012 i686 i686 i386 GNU/Linux

是什么导致了这些平台上的不同行为?

最佳答案

Python 询问终端正在使用什么编码,并在打印时将 unicode 字符串编码为字节。您的 Ubuntu 服务器未配置为 UTF-8 显示,您的 Mac 终端

参见 https://askubuntu.com/questions/87227/switch-encoding-of-terminal-with-a-command寻求有关切换终端区域设置的帮助。任何可以处理您尝试打印的特定代码点的语言环境都可以,但 UTF8 可以处理所有 Unicode。

您可以通过打印 sys.stdout.encoding 来查看 Python 检测到的内容:

>>> import sys
>>> sys.stdout.encoding
'UTF-8'

关于Python3 和编码 : different on linux and on OSX?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20022115/

相关文章:

ruby-on-rails - 有没有办法在 Ruby 中清除 "invalid byte sequence in UTF-8"错误的文件?

python - matplotlib 在 while 循环中更新绘图,以日期为 x 轴

python - 在python中求解colebrook(非线性)方程

c - 如何使用 fribidi 重新排序双向文本

python - Django 模板中的编码问题

python - 如何添加/替换/删除字符串中的转义字符 - Python

MySQL 插入和 unicode 字符

python - linux crontab 不能运行带图形界面的程序?

python - 用正则表达式替换单词列表

javascript - 在javascript中,我如何获得一个指示字符一般类别的值,例如java Character.getType?