我对unicode字符串serialport.write(" \ x23o0 \ x23f")不支持

时间:2016-01-23 02:22:43

标签: python-3.x unicode

我们在使用以下代码时遇到了困难

#Get the heading from the IMU
#Translate the IMU from magnetic north to true north since the calcs use true north
def getcurheading():
# The escape character for # is \x23 in hex
    serialport.write("\x23o0 \x23f")
    headresponse = serialport.readline()
#   print(headresponse)
    words = headresponse.split(",")
    if len(words) > 2:
        try:
            curheading = (float(words[0])) + 180
            if curheading + Declination > 360: curheading = curheading - 360 + Declination
            else: curheading = curheading + Declination
        except:
            curheading = 999
#   print(curheading)
        return curheading

以下是报告的错误:

Traceback (most recent call last):
  File "solarrobot7-core.py", line 256, in <module>
    if (getcurheading() < getsolarheading()) and (getsolarangle() > 2) and (getcurheading() != 999):
  File "solarrobot7-core.py", line 118, in getcurheading
    serialport.write("\x23o0 \x23f")
  File "/usr/local/lib/python3.2/dist-packages/serial/serialposix.py", line 518, in write
    d = to_bytes(data)
  File "/usr/local/lib/python3.2/dist-packages/serial/serialutil.py", line 58, in to_bytes
    raise TypeError('unicode strings are not supported, please encode to bytes: %r' % (seq,))
TypeError: unicode strings are not supported, please encode to bytes: '#o0 #f'

看起来我可以使用:

a_string = '\x23o0 \x23f Python'
by = a_string.encode('utf-8')
serialport.write(“\x23o0 \x23f “) a serialport.write(by)

这是对的吗?由于我不是编码员,我不确定此修复是否正确。我已经尝试过了,代码会继续,直到它抛出另一个似乎与此步骤相关的错误。这就是为什么我们在继续之前回溯以确定这是否正确。

1 个答案:

答案 0 :(得分:8)

在Python 3.X中,默认情况下,"abc"等字符串是Unicode字符串。必须对字符串进行编码以进行传输,或者只使用字节字符串b"abc"开始(请注意b)。这些都可以起作用:

serialport.write(b"\x23o0 \x23f")

或:

serialport.write("\x23o0 \x23f".encode('ascii'))

请注意,指定编码是可选的,默认为utf8

bytearray是字节字符串的可变形式,并不是真正需要的。它应该在没有Python 3编码的情况下给你一个错误:

>>> bytearray("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
>>> bytearray("abc",'ascii')
bytearray(b'abc')

您可以编辑字节数组:

>>> bytes = bytearray("abc",'ascii')
>>> bytes[1]=50
>>> bytes
bytearray(b'a2c')

但不是字节字符串:

>>> bytes = b'abc'
>>> bytes[1] = 50
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment