Pha*_*anh 6 python unicode python-2.7
我使用cmd Windows,chcp 65001,这是我的代码:
print u'\u0110 \u0110' + '\n'
Run Code Online (Sandbox Code Playgroud)
结果:
(a character cmd can't display) (character what i want)
Traceback (most recent call last):
File "b.py", line 26, in <module>
print u'\u0110 \u0110'
IOError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)
但是,当我使用这段代码时:
print u' \u0110 \u0110' + '\n'
Run Code Online (Sandbox Code Playgroud)
结果:
(a space)(charecter what i want) (character what i want)
Traceback (most recent call last):
File "b.py", line 26, in <module>
print u' \u0110 \u0110' + '\n'
IOError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)
我的屏幕:

我的问题是:
为什么python 2.7在打印unicode字符时需要空格?
如何修复IOError:[Errno 2]
在 Windows 上,您不能使用print.
有一些解决方法,如下所示:How to make python 3 print() utf8。但是,尽管这个问题的标题,你不能用它来实际打印使用代码页 65001 的 UTF-8,它会在完成后重复最后几个字节(正如我在下面进一步描述的那样)
例子:
#! python2
import sys
enc = sys.stdout.encoding
def outputUnicode(t):
bytes = t.encode(enc, 'replace')
sys.stdout.write(bytes)
outputUnicode(u'The letter \u0110\n')
Run Code Online (Sandbox Code Playgroud)
您可以将控制台的代码页更改为chcp包含要打印的字符的代码页。例如,在您的情况下,运行chcp 852.
如果我打印以下字符串,这些是我的盒子上的结果。我正在使用代码页 850,这是英语系统的默认值:
u"\u00abHello\u00bb" # "«Hello»"
u"\u0110" # "?"
u"\u4f60\u597d" # "??"
u"a\u2192b\u2192c" # "a?b?c"
Run Code Online (Sandbox Code Playgroud)
第一个命令将起作用,因为所有字符都在代码页 850 中。接下来的 3 个命令将失败。
UnicodeEncodeError: 'charmap' codec can't encode character u'\u0110' in position 0: character maps to <undefined>
将代码页更改为 852,第二个命令将起作用。
有一个 UTF-8 代码页 (65001),但它不适用于 python 2.7。
在 python 3.4 中,结果是一样的。如果您将代码页更改为 65001,您的损坏行为会稍微减少一些。
\Python34\python.exe -c "print(u'a\u2192b\u2192c')"
a?b?c
?c
C:\>
两个额外的字符 (?c) 是 Windows 上 C 标准库中非标准行为的结果。它们是字符串的 UTF-8 编码中最后 2 个字节的重复。
在Windows上,您可以使用打印任意字符串print(只要字体可以显示字符).只需printUnicode并配置您的环境.
例如,print_unicode.py:
#!/usr/bin/env python
print(u'\u0110\u0110')
Run Code Online (Sandbox Code Playgroud)
要打印到Windows控制台,您可以使用win-unicode-console包:
T:\> py -mpip install win-unicode-console
T:\> py -mrun print_unicode.py
Run Code Online (Sandbox Code Playgroud)
不要忘记配置适当的控制台字体.chcp在这种情况下,返回值无关紧要.
您可以手动调用WriteConsoleW()函数(Unicode API),将任意文本打印到Windows控制台.
您不需要第三方模块,将输出重定向到文件:
T:\> set PYTHONIOENCODING=utf-8
T:\> py print_unicode.py >output-utf-8.txt
Run Code Online (Sandbox Code Playgroud)
注意:run不使用模块.它适用于Python 2和3.
如果您不需要打印非BMP Unicode字符,那么您可以使用stdlib中的Python IDLE,例如,在Python 3中:
T:\> py -3 -midlelib -r print_unicode.py
Run Code Online (Sandbox Code Playgroud)
IDLE也可以在Python 2上使用,但调用是不同的.
| 归档时间: |
|
| 查看次数: |
1150 次 |
| 最近记录: |