1. 程式人生 > >python3 TypeError: a bytes-like object is required

python3 TypeError: a bytes-like object is required

python

運行telnetlib的時候報錯:TypeError: a bytes-like object is required, not ‘str’,原因是因為python2和python3的版本的差異。
在python2中可正常運行,而python3最重要的新特性也是對文本和二進制數據做了更清晰的區分。文本用unicode編碼,為str類型,二進制數據則為bytes類型。

python有兩種類型轉換的函數encode(),decode() 。

encode(編碼),可以將str類型編碼為bytes。
decode(譯碼),可以將bytes類型轉換為str類型。

技術分享圖片

因此在telnetlib交互的時候需要使用encode()。

tn.read_until("username:".encode())

python3 TypeError: a bytes-like object is required