python-can API

The python-can module is imported with:

import can

The two main python-can objects are:

  • Bus: Defines a CAN-bus interface[1]

  • Message: Defines a CAN-bus message (containing timestamp, ID, data, and more)[2]


Read messages

The most basic way of reading messages is demonstrated below.

import can

# Open log file
with can.LogReader("<LOG_FILE_PATH>") as reader:

    # Read messages
    for msg in reader:
        print(f"{msg.timestamp:.3f} {msg.arbitration_id:X} {msg.data.hex()}")

Replay messages

Logged messages can be replayed to any interface supported by python-can (e.g. csscan_serial) as demonstrated below.

import can

# Open bus
with can.Bus(interface="csscan_serial", channel="<CHANNEL>") as bus:

    # Open log file
    with can.LogReader("<LOG_FILE_PATH>") as reader:

        # Read messages using MessageSync to maintain original scheduling
        for msg in can.MessageSync(reader):

            # Replay message
            bus.send(msg)