0

我对python很陌生,我目前正在玩pyserial ,我基本上在做的是通过UART发送简单的命令。我有一个简单的命令是:

b'page 0\xff\xff\xff'

这基本上对硬件说“Go on page with index of 0”(这是一个Nextion 显示器)。我想要做的是以某种方式参数化这个字节数组能够动态传递0。我已经阅读了互联网上的不同主题,首先将其设为字符串,然后再使用bytearray,但我想知道是否无法使用字符串插值或其他方式将其应用到此处。

注意:末尾的\xff是特定于硬件的,并且必须存在。

4

3 回答 3

1

您是否查看了 python 中的字符串格式文档?

pageNum = 0
b'page {}\xff\xff\xff'.format(pageNum)

https://docs.python.org/3.4/library/string.html#string-formatting

于 2018-10-22T19:35:21.610 回答
0

如果有人仍然对我如何实现目标感兴趣,我会提出以下解决方案:

def __formatted_page_command(self, pageId): 
    # This is the representation of 'page 0\xff\xff\xff'. What we do here is to dynamically assign the page id. 
    commandAsBytesArray = [0x70,0x61,0x67,0x65,0x20,0x30,0xff, 0xff, 0xff] 
    commandAsBytesArray[5] = ord(str(pageId)) 
    return bytes(commandAsBytesArray)

所以,通过这种方式,我可以动态得到:

b'page 0\xff\xff\xff'
b'page 1\xff\xff\xff'
b'page 2\xff\xff\xff'

只需调用

self.__formatted_page_command(myPageId)
于 2018-10-23T21:57:16.170 回答
0

我正在寻找其他东西,但在结果中发现了这个。我忍不住添加了一个对我来说似乎很标准的解决方案。

在 Python 2 中有一个较低级别的格式化构造,它比以内置 str 的mod运算符.format的形式内置在语言中更快。有人告诉我,它要么共享代码,要么模仿 C 的 stdlib printf 风格。%

# you're pretty screwed if you have > 255 pages
# or if you're trying to go to the last page dynamically with -1
assert 0 <= pageId <= 0xff, "page out of range"
return b'page %s\xff\xff\xff' % pageId

还有其他选择,但我更喜欢老式的简单性。

于 2019-09-27T05:07:31.400 回答