作者Holocaust123 (奔跑的蜗牛)
看板Python
标题Re: [问题] 如何用Windows版的Python在cmd中印出档 …
时间Sat Apr 23 12:24:21 2011
: 其实用 chcp 就可以改了
: 也可以改成 UTF-8, code page 码是 65001
: 不过这样不够, 因为 Python 不认得 cp65001 是哪来的编码
: 详细可以看这个网页的内容(Stack Overflow 的讨论)http://goo.gl/qd4nY
稍微试了一下 结果是失败的 还在查原因
然而先不论结果 使用 chcp 65001 这方法有有几个问题:
1. 无法使用输入法
原因是 Windows 会根据 cmd 当前 code page 对应的 locale 来调用输入法
例如 cp950 => zh_TW => 新注音, 新仓颉, ...
而 cp65001 => 没有对应的locale => 没有输入法...
这样当碰上需要 user input 时就只能复制贴上了
2. 字宽问题
像是CJKW这种double-width的字元在code page为65001时几乎无法正确显示
稍微动个cursor就会破坏显示结果
http://i.imgur.com/W80lj.jpg
(给有心尝试的人 chcp 65001後要把字型改成Lucida或Consolas才能显示Unicode字元)
(一开始字型选项没有Consolas 要去改登录档才有 改法请参考这网站
http://blog.wolffmyren.com/2008/09/15/consolas-as-cmdexe-windows-console-font/ )
另外还有一些小问题
例如每次进入cmd就得手动输入chcp 65001等
(不过可以靠修改登录档解决:
http://superuser.com/questions/269818/change-default-code-page-of-windows-console-to-utf-8
但请注意
不要改OEMCP
否则下次开机会跟我一样进不了Windows(还好我是用VM测的) )
总之不太建议用这方法
: 上面讲了一个方法
: 另一个方法是设 PYTHONIOENCODING 这个环境变数
: 参考 http://wp.me/p3U05-aC
我先照他说的 新增一个环境变数 PYTHONIOENCODING 值为UTF-8
然後执行这段程式码:
import sys, locale, os
print(sys.stdout.encoding)
print(sys.stdout.isatty())
print(locale.getpreferredencoding())
print(sys.getfilesystemencoding())
print(os.environ["PYTHONIOENCODING"])
print(chr(246), chr(9786), chr(9787))
我的执行结果:
UTF-8
True
cp950
mbcs
UTF-8
Traceback (most recent call last):
File "a.py", line 7, in <module>
print(chr(246), chr(9786), chr(9787))
ValueError: chr() arg not in range(256)
请按任意键继续 . . .
跟他的执行结果不一样
他可以印出 chr(246), chr(9786), char(9787) 但我不行@@
(我在Windows跟Linux测 都印不出来)
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.30.46
1F:→ buganini:请看最後一则comment 04/23 13:34
哦哦...原来他是在py3k测那段code的
查了一下 py3k的chr()相当於py2.x的unichr()
修改code如下
import sys, locale, os
print(sys.stdout.encoding)
print(sys.stdout.isatty())
print(locale.getpreferredencoding())
print(sys.getfilesystemencoding())
print(os.environ["PYTHONIOENCODING"])
print type(unichr(246))
print unichr(246)
print unichr(9786)
print unichr(9787)
print unichr(246).encode('utf8')
print unichr(9786).encode('utf8')
print unichr(9787).encode('utf8')
print unichr(246).encode('big5')
print unichr(9786).encode('big5')
print unichr(9787).encode('big5')
执行结果(under Windows):
UTF-8
True
cp950
mbcs
UTF-8
<type 'unicode'>
绎
?
?
绎
?
?
Traceback (most recent call last):
File "a.py", line 14, in <module>
print unichr(246).encode('big5')
UnicodeEncodeError: 'big5' codec can't encode character u'\xf6' in position 0: illegal multibyte sequence
请按任意键继续 . . .
执行结果(under Linux)(我把印PYTHONIOENCODING那行注解了):
UTF-8
True
UTF-8
UTF-8
<type 'unicode'>
ö
☺
☻
ö
☺
☻
Traceback (most recent call last):
File "a.py", line 14, in <module>
print unichr(246).encode('big5')
UnicodeEncodeError: 'big5' codec can't encode character u'\xf6' in position 0: illegal multibyte sequence
为什麽那个人在Windows上印的出那些Unicode字元呢??
※ 编辑: Holocaust123 来自: 114.35.212.106 (04/23 14:14)
2F:→ bobhsiao:Python3.2的unichr()改成chr()了 05/14 00:18
3F:→ miku3920: 乾,不早说= =,害我半夜要等系统还原 03/30 04:38