Close bus in python-can

Question:

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?

Asked By: Dave

||

Answers:

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

Answered By: Ofer Sadan

There is reference to shutdown in the python-can doc here. This works for me under Windows. There is a noticeable delay when you call it, at least with the Ixxat CAN interface that I’m using.

# Open the interface
bus = can.interface.Bus(bustype='ixxat', ...)
.
.
.
# Close the interface
bus.shutdown()
Answered By: crj11
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.