1

我都在尝试将代码从 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'

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

4

1 回答 1

0

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

rospy.loginfo( init_msg.decode('utf-8')[0:(len(init_msg)-1)] )
于 2022-01-08T03:13:02.540 回答