[心得] Windows 输出至萤幕时避免编码错误

楼主: danny0838 (道可道非常道)   2015-05-03 20:24:59
如题,测试除错时常需要把字串内容输出到萤幕,
但 Windows cmd 的编码偏偏不是 UTF-8 ,
导致输出 Big5 不支援的字元会出错,
如果转成 bytes 输出又难以理解...
于是我写了以下程式码:
https://gist.github.com/danny0838/866077e30306a14247e9
这个 module 提供一个 safeprint 函数,
和内建的 print 相似,参数也一样,
但会在 unicode 无法正常转码到输出目标时自动做跳脱处理,
这样字串想输出到 (UTF-8) 档案能正常输出,
而输出到萤幕也不会因为萤幕编码不是 UTF-8 发生烦人的 Exception。
safeprint 比内建 print 函数多了一个 errors 参数,
可用值有 ignore, replace, backslashreplace, xmlcharrefreplace, (strict) 几种,
代表各种遇到无法转码时采用的跳脱策略,大家可自行试试。
其他程式只要 from safeprint import safeprint 以后用 safeprint 即可。
或者暴力一点 from safeprint import safeprint as print
以后 print 就是 safeprint 了 ^^
如有错误或可优化的地方欢迎提供
另外我想问个问题:
为什么 Windows cmd 在 chcp 65001 以后 UTF-8 字符印到萤幕还是一团乱呢?
作者: uranusjr (←這人是超級笨蛋)   2015-05-03 21:13:00
因为 command pompt 对 CP65001 的支援很差, 怪微软吧建议可以稍微整理一下把它放上 PyPI, 用起来会更方便

Links booklink

Contact Us: admin [ a t ] ucptt.com