2018年9月24日 星期一

python 2.7 exception message 無法印出中文

使用 python 2.7 時遇到印出 exception message 時變成一串 binary string,例如 open com port fail 時,會收到 SerialException,內容如下

could not open port '123': WindowsError(2, '\xa8t\xb2\xce\xa7\xe4\xa4\xa3\xa8\xec\xab\xfc\xa9w\xaa\xba\xc0\xc9\xae\xd7\xa1C')

Google 找了很多資料,有講到用 CP950 decode 的,還有其他一些 decode 方式,不過試過後都沒用,有可能是因為網路上的範例所用的字串中還是 binary 的 data,而我遇到的情況是中文已經被轉為 \xa8t 這樣的 ASCII 字元了,所以需要找的解法應該是可以將 ASCII code 轉為 binary data 的方案

最後發現,用 "string_escape" decode 就可以達成
str(e).decode('string_escape')
string_escape 的用途是把遇到 \x 後面的字串轉為 binary 的 data,而其他一般的字串就不作更動,所以只要把 exception message 整串丟給它,就會幫你轉好了,非常方便

沒有留言:

張貼留言