0

I am quite new to python and I am currently playing around with pyserial and what I am basically doing is sending simple commands via UART. A simple command that I have is:

b'page 0\xff\xff\xff'

which basically says to the hardware "Go on page with index of 0" (It is a Nextion display). What I want to do is to somehow parameterize this byte array be able to dynamically pass the 0. I've read different topics on the internet of first making it a string and later one use bytearray but I was wondering if it is not possible to apply it here somehow using string interpolation or something.

NOTE: The \xff's at the end are hardware specific and must be there.

user2128702
  • 2,059
  • 2
  • 29
  • 74

3 Answers3

1

Did you check out the string format docs in python?

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

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

ThinkBonobo
  • 15,487
  • 9
  • 65
  • 80
  • I am getting an error using this approach stating: AttributeError: 'bytes' object has no attribute 'format' – user2128702 Oct 22 '18 at 19:46
  • @user2128702, that's an unusual error message. AFAIK, Python 2.7 doesn't _have_ a type named "bytes". Python 3, however, does. Are you entirely sure you're using Python 2.7? – Kevin Oct 22 '18 at 19:54
  • The exact version checked using 'python -V' is 2.7.13 – user2128702 Oct 22 '18 at 20:07
  • With Python 2, `r'page {}\xff\xff\xff'.format(pageNum)` – dawg Oct 22 '18 at 20:30
  • @dawg this one doesn't seem to be an option also. I keep on getting: TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq)) – user2128702 Oct 22 '18 at 22:43
0

If someone is still interested of how I achieved my goal, I came to the following solution:

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)

So, in this way, I can dynamically get:

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

just by calling

self.__formatted_page_command(myPageId)
user2128702
  • 2,059
  • 2
  • 29
  • 74
0

I was searching for something else but found this in results. I could not help myself but to add a solution that seems so standard to me.

In Python 2 there is a lower level formatting construct that is faster than .format that is built into the language in the form of the builtin str's mod operator, %. I've been told that it either shares code with or mimicks C's stdlib printf style.

# 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

There are other options but I prefer old-school simplicity.

parity3
  • 643
  • 9
  • 18