Home  >  Q&A  >  body text

python 运行.py文件 一加上decode()就报错。。

python 运行.py文件 一加上decode()就报错。。

文件如下:

import socket

HOST, PORT = '127.0.0.1', 8888

listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print ('Serving HTTP on port %s ...' % PORT)
while True:
    client_connection, client_address = listen_socket.accept()
    request = client_connection.recv(1024)
    print (request.decode('utf-8'))

    http_response = """
HTTP/1.1 200 OK

Hello, World!
""".encode("utf-8")
    client_connection.sendall(http_response)
    client_connection.close()

其中的 print (request.decode('utf-8'))不加decode()还能运行,一转码不管decode()括号里面写任何东西或者空着就会报错。。
错误如下所示:

websercer1.py文件我确定是utf-8编码格式的,真心不知道这是什么回事了。。
哪位知道麻烦告知,拜谢。。。

PHP中文网PHP中文网2741 days ago440

reply all(3)I'll reply

  • 阿神

    阿神2017-04-18 09:23:47

    decode is decoding.
    It has nothing to do with the encoding of the websercer1.py file.

    request.decode('encoding') #refers to what encoding you use to decode the request...

    Your error may have been encoded in UTF-8

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:23:47

    Although you are sure that it is UTF-8 encoding, it is recommended that you save it to a txt file first and take a look.
    A stupid method I often use to crawl data is to write things into txt without thinking to see what is inside, like this Better debug

    import codecs
    with codecs.open('abc.txt','w','utf-8') as f:
        #do your encode decode    
        f.write(request) # 可能是request.content? request.text?
       
    #then do something with abc.txt

    If the utf-8 format of codecs cannot be saved as txt, then your content should not be utf-8

    reply
    0
  • 迷茫

    迷茫2017-04-18 09:23:47

    Your encoding is originally UTF-8, so there is no need to encode or decode. That encode is redundant, (and you also wrote it wrong, you need to decode first, and then encode, so it is redundant)
    http_response = """HTTP/1.1 200 OK Hello, World!""".decode('utf- 8').encode("utf-8")
    It didn’t work in the end. There may be something wrong with the socket code. Please check again

    reply
    0
  • Cancelreply