【问题标题】:"AttributeError: 'bytes' object has no attribute 'encode' ""AttributeError: 'bytes' 对象没有属性 'encode'"
【发布时间】:2016-11-14 14:55:11
【问题描述】:

我在尝试运行我的代码时遇到以下错误。这是一个sn-p:

import time;
from socket import*
from pip._vendor.distlib.compat import raw_input

pingCount = 0
minTime = 0
maxTime = 0
counter = 0
totalTime = 0
message = 'test'
packetsLost = 0

#Sends 10 pingcounts as setup_testing_defaults
while pingCount < 11:
counter +=1

#Creates a UDP Socket
clientSocket = socket(AF_INET, SOCK_DGRAM)

#Sets timeout value for each one to 1 second
#The timeout function determines how long till it expires
clientSocket.settimeout(1)

#Creating the paramaters for sendTo
#SendTo sends the ping to the socket
clientSocket.sendto(message.encode("utf-8"),('127.0.0.1',12000))    

#time() yields the current time in milliseconds
start = time.time()

#Trying to print data received from the server
try: #etc...

代码运行了几次迭代(通常最多 3 次,然后因上述错误而崩溃。我不太确定发生了什么,所以任何建议都会很棒,谢谢!

【问题讨论】:

  • 在 while 循环的第二次或第三次迭代中,message 可能是 bytes 类型。当然,哪个没有编码方法。
  • 这段代码对我有用。也许是尝试后的代码?
  • 投票结束基于有问题的代码没有出现错误的报告。此外,您还有缩进问题; while 命令后面的代码需要另一个缩进级别才能实际包含在 while 循环中。如果不修改,你的代码会在那里抛出语法错误。
  • 需要注意的一些事情:您的 raw_input 似乎错误(即:从 pip 导入?)...如果您使用的是 Python 3,则应该使用 input 代替。另外,请包括实际的堆栈跟踪,仅您的示例部分代码不足以诊断它。

标签: python python-3.x


【解决方案1】:

这可能是代码中稍后将message 重新分配给bytes 对象的东西——也许您正在重新分配从clientSocket 接收到的数据?如果是这样,则返回 clientSocket 的数据是 bytes 对象,并且需要为 decoded,类似于您使用 message.encode() 通过客户端发送文本数据的方式。

关于使用bytes对象进行IO通信有一个很好的解释——特别是如果你习惯了python2.x的做事方式——here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2021-04-23
    • 1970-01-01
    • 2020-11-04
    相关资源
    最近更新 更多