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

fra*_*e09 4 unicode python-3.x

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

#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
Run Code Online (Sandbox Code Playgroud)

这是报告的错误:

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'
Run Code Online (Sandbox Code Playgroud)

看起来我可以使用:

a_string = '\x23o0 \x23f Python'
by = a_string.encode('utf-8')
serialport.write(“\x23o0 \x23f “) a serialport.write(by)
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*nen 8

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

serialport.write(b"\x23o0 \x23f")
Run Code Online (Sandbox Code Playgroud)

要么:

serialport.write("\x23o0 \x23f".encode('ascii'))
Run Code Online (Sandbox Code Playgroud)

请注意,指定编码是可选的,默认为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')
Run Code Online (Sandbox Code Playgroud)

您可以编辑字节数组:

>>> bytes = bytearray("abc",'ascii')
>>> bytes[1]=50
>>> bytes
bytearray(b'a2c')
Run Code Online (Sandbox Code Playgroud)

但不是字节字符串:

>>> 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
Run Code Online (Sandbox Code Playgroud)