python-can

The python-can library provides Controller Area Network support for Python, providing common abstractions to different hardware devices, and a suite of utilities for sending and receiving messages on a CAN bus.

python-can runs any where Python runs; from high powered computers with commercial CAN to usb devices right down to low powered devices running linux such as a BeagleBone or RaspberryPi.

More concretely, some example uses of the library:

  • Passively logging what occurs on a CAN bus. For example monitoring a commercial vehicle using its OBD-II port.

  • Testing of hardware that interacts via CAN. Modules found in modern cars, motocycles, boats, and even wheelchairs have had components tested from Python using this library.

  • Prototyping new hardware modules or software algorithms in-the-loop. Easily interact with an existing bus.

  • Creating virtual modules to prototype CAN bus communication.

Brief example of the library in action: connecting to a CAN bus, creating and sending a message:

 1#!/usr/bin/env python
 2
 3"""
 4This example shows how sending a single message works.
 5"""
 6
 7import can
 8
 9
10def send_one():
11    """Sends a single message."""
12
13    # this uses the default configuration (for example from the config file)
14    # see https://python-can.readthedocs.io/en/stable/configuration.html
15    with can.interface.Bus() as bus:
16
17        # Using specific buses works similar:
18        # bus = can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000)
19        # bus = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=250000)
20        # bus = can.interface.Bus(bustype='ixxat', channel=0, bitrate=250000)
21        # bus = can.interface.Bus(bustype='vector', app_name='CANalyzer', channel=0, bitrate=250000)
22        # ...
23
24        msg = can.Message(
25            arbitration_id=0xC0FFEE, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=True
26        )
27
28        try:
29            bus.send(msg)
30            print(f"Message sent on {bus.channel_info}")
31        except can.CanError:
32            print("Message NOT sent")
33
34
35if __name__ == "__main__":
36    send_one()

Contents:

Known Bugs

See the project bug tracker on github. Patches and pull requests very welcome!

Documentation generated

Dec 01, 2021