[心得] Windows 輸出至螢幕時避免編碼錯誤

看板Python作者 (道可道非常道)時間9年前 (2015/05/03 20:25), 9年前編輯推噓0(002)
留言2則, 1人參與, 最新討論串1/1
如題,測試除錯時常需要把字串內容輸出到螢幕, 但 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 字元印到螢幕還是一團亂呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.137.14.228 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1430655902.A.C82.html ※ 編輯: danny0838 (220.137.14.228), 05/03/2015 20:25:50

05/03 21:13, , 1F
因為 command pompt 對 CP65001 的支援很差, 怪微軟吧
05/03 21:13, 1F

05/03 21:14, , 2F
建議可以稍微整理一下把它放上 PyPI, 用起來會更方便
05/03 21:14, 2F
文章代碼(AID): #1LHXEUo2 (Python)