相关疑难解决方法(0)

为什么Python在默认编码为ASCII时会打印unicode字符?

从Python 2.6 shell:

>>> import sys
>>> print sys.getdefaultencoding()
ascii
>>> print u'\xe9'
é
>>> 
Run Code Online (Sandbox Code Playgroud)

我希望在print语句之后有一些乱码或错误,因为"é"字符不是ASCII的一部分,我没有指定编码.我想我不明白ASCII是默认编码的意思.

编辑

我将编辑移动到了答案部分并按照建议接受了它.

python unicode encoding ascii python-2.x

137
推荐指数
3
解决办法
8万
查看次数

在Python中通过sys.stdout编写unicode字符串

假设一个人不能使用print(从而享受自动编码检测的好处).所以这让我们失望了sys.stdout.但是,如果不做任何明智的编码sys.stdout是如此愚蠢.

现在,您可以阅读Python维基页面PrintFails并尝试以下代码:

$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \
  sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout);
Run Code Online (Sandbox Code Playgroud)

然而,这也不起作用(至少在Mac上).太明白为什么:

>>> import locale
>>> locale.getpreferredencoding()
'mac-roman'
>>> sys.stdout.encoding
'UTF-8'
Run Code Online (Sandbox Code Playgroud)

(UTF-8是终端理解的).

所以将上面的代码更改为:

$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \
  sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout);
Run Code Online (Sandbox Code Playgroud)

现在,unicode字符串被正确发送到sys.stdout终端上并在终端上正确打印(sys.stdout连接到终端).

这是编写unicode字符串的正确方法sys.stdout还是我应该做的其他事情?

编辑:有时 - 比如说,当输出到less- 时sys.stdout.encoding将是None.在这种情况下,上面的代码将失败.

python unicode macos terminal stdout

17
推荐指数
5
解决办法
3万
查看次数

标签 统计

python ×2

unicode ×2

ascii ×1

encoding ×1

macos ×1

python-2.x ×1

stdout ×1

terminal ×1