gpt4 book ai didi

python - Python的decode() 'utf-8'编解码器无法解码位置0 : invalid start byte的字节0xff

转载 作者:行者123 更新时间:2023-12-03 11:50:24 25 4
gpt4 key购买 nike

我正在构建此套接字应用程序,并且每次遇到以下错误时:
UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:无效的起始字节

这是来自服务器的相关行:

    filename = client_sock.recv(1024).decode()
filesize = client_sock.recv(1024).decode()

以下是来自客户的相关信息:
    self.sock.send(file_dir.encode())
self.sock.send(str(filesize).encode())

该错误消息发生在服务器的第二行。 (文件大小=)
这是显示客户端将发送到服务器的内容的打印品。
    print(file_dir) # Output is D:/Statispic2/Photos/photo3.jpg
print(filesize) # Output is 96523

该错误有时仅会发生,这确实很奇怪。我看过其他提出类似问题的问题,但是它们的解决方案要么无效,要么不相关。

如果您想查看整个代码或有其他疑问,请告诉我!
非常感谢!

最佳答案

发生错误是因为无法将该字节解码为utf-8,您可以将其作为异常处理,在异常处理时将其解码为“utf-16”:

filename = client_sock.recv(1024)
filesize = client_sock.recv(1024)
try:
decoded_filename = filename.decode()
decoded_filesize = filename.decode()
except UnicodeDecodeError:
decoded_filename = filename.decode('utf-16')
decoded_filesize = filename.decode('utf-16')

另外,您可以在解码期间忽略异常,但是不建议这样做...
filename = client_sock.recv(1024).decode("utf-8", "ignore")
filesize = client_sock.recv(1024).decode("utf-8", "ignore")

关于python - Python的decode() 'utf-8'编解码器无法解码位置0 : invalid start byte的字节0xff,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61820975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com