错误 python 代码:属性错误:'bytes'对象没有属性'encode'



我都在尝试将代码从python2.7传递到3.8,但我被以下代码卡住了:

def serial_handle(self):
# Serial initialization
try:
self.serial.reset_input_buffer()
rospy.loginfo("Reaching for serial")
rospy.loginfo("Here are the first 5 data readings ...")
time.sleep(1)
self.serial.reset_input_buffer()
init_msg = self.serial.readline()
for x in range(0, 5):
#init_msg = self.serial.read(10)
init_msg = self.serial.readline()
rospy.loginfo( init_msg.encode('utf-8')[0:(len(init_msg)-1)] )
except serial.serialutil.SerialException:
rospy.logerr("Port timeout after %d seconds at: %s", self.timeout, self.device_port)
self.serial.close
sys.exit(0)

# sent start signal
self.serialOK = True
self.serial.write( 'B'.encode('ascii') )
time.sleep(0.08)        # for Arduino to reboot

因为它总是向我发送这个错误:

Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/paloverde/dev_ros_encoders/src/serial_odom/script/v0.3/serial_odom.py", line 95, in serial_handle
rospy.loginfo( init_msg.encode('utf-8')[0:(len(init_msg)-1)] )
AttributeError: 'bytes' object has no attribute 'encode'

有人知道可以为此实施什么解决方案吗?

看起来您有一个字节字符串init_msg,要将其转换为unicode字符串。你可能想使用解码而不是编码:

rospy.loginfo( init_msg.decode('utf-8')[0:(len(init_msg)-1)] )

最新更新