python3 TypeError: a bytes-like object is required, not 'str'

在學習《Python web開發學習實錄》時,

例11-1:

# !/usr/bin/env python
# coding=utf-8
import socket
sock = socket.socket()
sock.bind(('localhost', 8080))
sock.listen(5)
while True:
    connection,address = sock.accept()
    try:
        connection.settimeout(5)
        buf = connection.recv(1024)
        if buf == '1':
            connection.send("Welcome to server!")
        else:
            connection.send("please go out!")
    except socket.timeout:
        print('time out')
    connection.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

編寫web服務器報TypeError: a bytes-like object is required, not ‘str’錯誤,後來查到是因爲python2和python3的版本有些差異,而python3最重要的新特性也是對文本和二進制數據做了更清晰的區分。文本用unicode編碼,爲str類型,二進制數據則爲bytes類型。

python有兩種類型轉換的函數encode(),decode() 
encode(編碼),可以將str類型編碼爲bytes。 
decode(譯碼),可以將bytes類型轉換爲str類型。

知道了上面兩點要解決這個錯誤也就不麻煩了, 
ypeError: a bytes-like object is required, not ‘str’ 
錯誤原因是TypeError,因爲要求bytes類型卻給了str類型,那麼只需要在send函數參數中加上encode()方法就行。 
connection.send("please Go out!".encode())

發佈了29 篇原創文章 · 獲贊 17 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章