I am using python-can
to send CAN messages like this:
JavaScript
x
10
10
1
import can
2
3
bus2 = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000)
4
5
msg = can.Message(
6
arbitration_id=0x42, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=False
7
)
8
9
bus2.send(msg)
10
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:
JavaScript
1
2
1
bus2.close()
2
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?
Advertisement
Answer
The Bus
object should be used inside a with
statement to be closed properly.
JavaScript
1
5
1
import can
2
with can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000) as bus2:
3
msg = can.Message(arbitration_id=0x42, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=False)
4
bus2.send(msg)
5
You should be able to send more messages inside this open block, but after this block the bus will be closed properly