背景
自動化測試調用HTMLTestRunner生成測試報告的時候,出現了編碼錯誤,錯誤如題
原因
搜索了很多資料,得出的結論是python的str默認是ascii編碼,和unicode編碼沖突,就會報這個錯誤
解決方法
網上的資料推薦在代碼中加上如下幾句可以解決這個問題:
1 import sys 2 reload(sys) 3 sys.setdefaultencoding('utf8')
深入
博主在后來又遇到過多次編碼錯誤,最常遇到的就是下面這個:
“UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)“
后來學習了unicode和utf-8相關的內容,慢慢的對這一塊有了一定的認識:
unicode指的是萬國碼 是一種"字碼表" 而utf-8是這種字碼表儲存的編碼方法,編成bytecode儲存,unicode還可以編碼utf-16,utf-7等其他方式
Python中字符串類型分為兩種型態:byte string、unicode string Python腳本頂部設定了“ #coding=utf-8”后所有帶有中文的都會被宣告為utf-8的byte string,但是,在函數中所產生的字符串,又會是unicode string。其實兩者都能表示中文,但是不代表能夠混用,混用就會出錯
例如:
response.out.write("你好"+request.get("argu"))
中文字符“你好”會被宣告為byte string,而request.get()的結果是unicode string
Python會自動常識吧前面的“你好”轉為unicode
但是預設的解碼器是ascii,所以轉換不出來,就報了上面的錯誤。
一勞永逸的方法
綜上所述,一勞永逸的解決的方法有3種
全部轉為byte string (response.out.write("你好"+request.get("argu").encode('utf-8')))
全部轉為unicode string (response.out.write(u"你好"+request.get("argu")))
更改設定預設解碼器為utf-8
P.S.資料庫存入和讀取以及request拿到的參數預設就都是unicode string,若是要把byte string轉unicode string可以這樣轉unicode(unicodestring,"utf-8")
這樣就再也不會有"UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)"的問題產生了 遇到噴出這種錯誤幾乎都可以用這2種方法解決
我個人是覺得用第一種全都轉byte string比較好
因為一但用了unicode string 以后有中文字串前面都要掛個u 看起來不是很直覺 而且容易漏掉
不如在遇到函式有中文結果(或是資料庫撈出來的結果)直接都encode成utf-8就好