解決 Python TypeError: a bytes-like object is required, not ‘str’


剛剛將一個在 CentOS 7 用 Python 2 執行的 Python 程式, 移植到 CentOS 8 的 Python 3 執行, 執行時出現以下報錯, 解決方法紀錄一下:

TypeError: a bytes-like object is required, not ‘str’

問題出在 Python 2 及 Python 3 在套接字返回值編碼上的分別, Python 下的 bytes 及 str 兩種資料型態可以用 encode() 及 decode() 互換。
encode() : 把 str 轉換成 bytes.
decode() : 把 bytes 轉換成 str.

解決方法很簡單, 只要把出現問題的地方加入 decode() 可, 例如以下程式碼出現問題:

改成

Tags:

Leave a Reply