Is it possible to interrupt a try-except code in python with gpio interrupt to generate exception? In the "try" part i'm openning a socket and use socket.serve_forever(). I want to make a hard-reboot to the program, using a reboot button that is connected to a gpio. What I want is that when button is pressed-an interrupt/exception is invoked and it goes right to the "except" part (going out of an infinite loop) , closing the socket and restart the program (later openning the socket again).

Example for code:

    ... #code
    print "button was pressed, closing socket and restart program..."

I think the best you can do is use a gpio event callback to set a shutdown flag and have your socket loop act on the flag when it is seen.

If the socket loop may not be entered for some time then you will have to find an action which triggers a socket message.

Alternatively use your gpio event callback to force a restart itself.


Have a look here, it explains how GPIO Interruptions works

You can modulate interruption like that:

GPIO.add_event_detect(channel, GPIO.RISING)
if GPIO.event_detected(channel):
    print('Button pressed')here

You'll be able to break a loop or call a function !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.