python - 为什么在将 Unicode 写入 CMD 时会出现 IOErrors? (代码页 65001)

标签 python windows windows-8

我在 Windows 8 中使用 CMD,并将代码页设置为 65001 (chcp 65001)。我使用的是 Python 2.7.2 (ActivePython 2.7.2.5),并将 PYTHONSTARTUP 环境变量设置为“bootstrap.py”。

bootstrap.py:

import codecs
codecs.register(
    lambda name: name == 'cp65001' and codecs.lookup('UTF-8') or None
)

这让我打印 ASCII:

>>> print 'hello'
hello
>>> print u'hello'
hello

但是当我尝试打印带有非 ASCII 字符的 Unicode 字符串时出现的错误对我来说毫无意义。在这里,我尝试打印一些包含北欧符号的字符串(为了便于阅读,我在打印之间添加了额外的换行符):

>>> print u'æøå'
��øåTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory

>>> print u'åndalsnes'
��ndalsnes

>>> print u'åndalsnesæ'
��ndalsnesæTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] Invalid argument

>>> print u'Øst'
��st

>>> print u'uØst'
uØstTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] Invalid argument

>>> print u'ØstÆØÅæøå'
��stÆØÅæøåTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] Invalid argument

>>> print u'_ØstÆØÅæøå'
_ØstÆØÅæøåTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] Invalid argument

如您所见,它并不总是会引发错误(甚至不会每次都引发相同的错误),北欧符号只是偶尔会正确显示。

有人可以解释这种行为,或者至少帮助我弄清楚如何正确地将 Unicode 打印到 CMD?

最佳答案

试试这个:

# -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    print u'æøå'

利用 from __future__ import unicode_literals交互式 python session 中很有用。

当然可以使用 WriteConsoleW 将 Unicode 成功写入控制台。这与控制台代码页无关,包括 65001。代码 here这样做(它适用于 Python 2.x,但无论如何您都会从 C 调用 WriteConsoleW)。

WriteConsoleW 有一个我知道的错误,即它 fails when writing more than 26608 characters at once .通过限制在单个调用中传递的数据量,这很容易解决。

字体不是 Python 的问题,但编码才是。仅仅因为某些用户可能没有选择可以显示这些字符的字体而无法输出正确的字符是没有意义的。这个错误应该重新打开。

(为了完整起见,可以使用 Lucida Console 和 Consolas 以外的字体在控制台上显示 Unicode,但它 requires a registry hack。) 希望对您有所帮助。

关于python - 为什么在将 Unicode 写入 CMD 时会出现 IOErrors? (代码页 65001),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13452916/

相关文章:

python - gensim 中的 get_document_topics 和 get_term_topics

python - 如何删除 Squish 事件处理程序?

windows - 通过 PsExec 在远程计算机中执行批处理文件

python - 在 Windows 上将 Python 图像库与 VirtualEnv 结合使用

visual-studio - 如何修复 win 8 认证报告中的 Debug App Check

python - 如何使用 BeautifulSoup 获取 colindex 数字?

python - 拓扑排序(卡恩算法)的麻烦

c++ - 为什么没有 InterlockedExchange Subtract 64?

windows-8 - WinRT Metro 应用程序是否交叉兼容(x86/64 和 ARM)?

html - 基于 Windows 8 XAML 的应用程序是否明显快于 HTML/CSS 应用程序?