gpt4 book ai didi

python-3.x - Unicode 字符串serialport.write ("\x23o0\x23f") 不支持

转载 作者:行者123 更新时间:2023-12-03 16:29:23 24 4
gpt4 key购买 nike

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

#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)

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

最佳答案

在 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

关于python-3.x - Unicode 字符串serialport.write ("\x23o0\x23f") 不支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34958926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com