End a endless loop clos can bus

I have a loop scanning a CAN Bus and I want do end it clean with a i.e. “q” from keybord, so I can have a clean bus.shutdown().

If I do a hard stoop I get a message bus was not shutdown
an input() stops the loop until key pressed, but the loop should run until I like to stop

You can put the loop inside a try block, with the cleanup in a except KeyboardInterrupt block.

try:
    while True:
        # Scan bus.
except KeyboardInterrupt:
    bus.shutdown()

This let’s you exit the loop cleanly by issuing a keyboard interrupt, i.e. ctrl+c.

2 Likes