Win7 + Python 2.7.8,源文件聲明 # -*- coding: utf-8 -*-,u'中文' 正常輸出;但在 EditPlus 內運行報錯。
-u (無緩衝) 或環境變量 PYTHONIOENCODING=utf-8。import sys
import os
os.system('chcp 65001') # 切換到 UTF-8
# 之後 print 正常
-u "$(FilePath)"$(FileDir)PYTHONIOENCODING=utf-8。import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
Python 3 默認源碼 UTF-8、字符串為 Unicode、print 為函數、控制台編碼處理更完善。強烈建議新專案直接使用 Python 3.8+。
| 概念 | Python 2 | Python 3 |
|---|---|---|
| 源碼默認編碼 | ASCII(需聲明) | UTF-8 |
| 字符串類型 | str=bytes, unicode=text | str=text, bytes=bytes |
| 語句 | 函數 | |
| 控制台編碼處理 | 極易出錯 | 自動適配 |
EditPlus 運行 Python 2 亂碼本質是「源碼 UTF-8」與「控制台 GBK」不匹配。配置 PYTHONIOENCODING=utf-8 或遷移 Python 3 可徹底解決。