pythoncan-buspython-can

Close bus in python-can


I am using python-can to send CAN messages like this:

import can

bus2 = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000)

msg = can.Message(
    arbitration_id=0x42, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=False
)

bus2.send(msg)

The script works fine, but when I run it for a 2nd time, it results in an error, because the bus is still open from the previous time. I think I need something like this at the end of my script:

bus2.close()

However, this does not exist and I can't seem to find the proper way to do it in the python-can documentation. How can I properly close the bus in order to be able to use it again the next time?


Solution

  • The Bus object should be used inside a with statement to be closed properly.

    import can
    with can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000) as bus2:
        msg = can.Message(arbitration_id=0x42, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=False)
        bus2.send(msg)
    

    You should be able to send more messages inside this open block, but after this block the bus will be closed properly

    See the docs