I am working with some hardware that can be controlled via hex commands. I already have some snippets of Python code I use for telnet control of other devices that use ASCII commands.
How do I go about sending hex commands? For instance, how would I modify skt.send('some ascii command\r')
with hex value, and what's the best data type for storing those values?
Thanks.
In Python 2, use string literals:
skt.send('\x12\r')
In Python 3, use bytes literals or bytes.fromhex
:
skt.send(b'\x12\r')
skt.send(bytes.fromhex('12 0d'))
In either case, the bytearray
type will probably be useful as it is a mutable (modifiable) type that you can construct with integers as well as a bytes literal:
skt.send(bytearray([0x02, 0x03, 0x00, 0x00, 0x05]))
Under Python 3, you have the great bytes.fromhex()
function as well.
>>> bytes.fromhex('AA 11 FE')
b'\xaa\x11\xfe'
>>> bytes.fromhex('AA11FE')
b'\xaa\x11\xfe'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With