python pipe 到 more 或檔案會出現 UnicodeDecodeError

好久沒有更新這個部落格了。今天剛好有東西可以 share 一下。

這個問題困繞我很多次, 不過我之前都沒有仔細看到底是怎麼回事。今天查了一下, UnicodeDecodeError when redirecting to file 這篇就寫得很清楚。基本上就是用 pipe 導出去的時候無法判別 encoding, 所以非 ASCII 的就會出錯。這篇文章提到用下列的方式就可以解決這個問題:

import codecs import locale import sys

# Wrap sys.stdout into a StreamWriter to allow writing unicode.

import codecs
import locale
import sys
 
# Wrap sys.stdout into a StreamWriter to allow writing unicode.
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
uni = u"\u001A\u0BC3\u1451\U0001D10C"
print uni

這樣不管是直接執行

yychen$ python test.py

或是把他導出來

yychen$ python test.py > test.txt 
yychen$ python test.py | more

都 ok 了。