gpt4 book ai didi

python - 将字符串发送到 serial.to_bytes 不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 07:34:31 25 4
gpt4 key购买 nike

我正在尝试发送一个包含命令的字符串变量。

像这样:

value="[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
self.s.write(serial.to_bytes(value))

上面那个失败了。不会报错。

但是当我发送这样的值时它起作用了:

self.s.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))

我也试过像这样发送字符串:

self.s.write(serial.to_bytes(str(value)))

还是不行。有人可以告诉我如何通过存储在字符串中来发送值吗?

我想做这件事:

value="[0x"+anotherstring+",0x"+string2+"0x33, 0x0a]"

并发送值。

谢谢!

最佳答案

serial.to_bytes将序列作为输入。您应该删除 value 周围的双引号以传递整数序列而不是 str 表示您要传递的序列:

value = [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]
self.s.write(serial.to_bytes(value)) # works now

在第一种情况下,您发送了一个表示 [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]” 的字节序列。现在,您将按预期发送序列 [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]


如果要发送字符串,只需将其作为bytes发送即可:

# Python 2
self.s.write('this is my string')
text = 'a string'
self.s.write(text)

# Python 3
self.s.write(b'this is my string')
text = 'a string'
self.s.write(text.encode())

对于一个序列:

for value in values:
# Python 2
self.s.write(value)

# Python 3
self.s.write(value.encode())

关于python - 将字符串发送到 serial.to_bytes 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39424865/

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