How to remove ASCII formatted characters from my CAN messages in Python?

69 views Asked by At

I would like to remove ASCII characters from my bytearray and see it containing hexadecimal numbers. To explain it better: I receive CAN messages from CANbus using the pyton-can library and catch them to store in a message variable. As I print it I see:

bytearray(b'\x00\x00^]b\tb\xd9')

But I don't want to see ASCII characters, I want it to print this as for example b'\x00\x00\x01\x65\xA5\x12\x1A\xBB

So what should I do?

My code now looks like:

#receiving CAN Bus messages here
bus = can.interface.Bus(interface='kvaser', channel=0, bitrate=1000000)
byte_index_to_check = 1
msg = can.Message(arbitration_id=0x007)
bus.send(msg)
recvMsg = bus.recv(timeout=0.5)
message = bus.recv()
received_message = hex(message.data[byte_index_to_check])

last_message = message
last_received = received_message
print("last message",last_message.data)
2

There are 2 answers

0
dda On

You don't so much want to remove characters, as convert them to HEX. The binascii library does just that:

binascii.b2a_hex(message, b' ')
0
tripleee On

If you want to keep the same code, you could inherit from bytes and override the __repr__ method.

class hexbytes(bytes):
    def __repr__(self):
        return r"b'" + "".join(hex(b).replace("0", "\\") for b in self.__bytes__()) + "'"
...
message = hexbytes(bus.recv())