🌐
MicroPython
docs.micropython.org › en › latest › reference › isr_rules.html
Writing interrupt handlers — MicroPython latest documentation
Consequently the main program should create all necessary globals before starting a process that generates hard interrupts. Application code should also avoid deleting globals. MicroPython supports integers of arbitrary precision. Values between 2**30 -1 and -2**30 will be stored in a single machine word. Larger values are stored as Python objects.
🌐
David Hamann
davidhamann.de › posts › handling and confirming (interrupt) signals in python
Handling and confirming (interrupt) signals in Python | David Hamann
September 29, 2022 - Once set, we overwrite the default behavior and won’t get any KeyboardInterrupts anymore (although you could easily recreate the default behavior by setting the previous handler again, which is returned by signal()). Running the program and then sending an interrupt (<Control-c>) will now look something like this: $ python3 demo.py .....^CHandling signal 2 (SIGINT).
Discussions

performance - Real-time interrupts in Python - Stack Overflow
I have a Python 2.7 program running an infinite while loop and I want to incorporate a timer interrupt. What I aim to do is to set off a timer at some point in the loop, and when 5 seconds have ela... More on stackoverflow.com
🌐 stackoverflow.com
Interrupt function execution from another function in Python - Stack Overflow
I have a function a doing some tasks and another function b being a callback to some events. Whenever an event happens, function b is called and I would like to make it able to interrupt the execut... More on stackoverflow.com
🌐 stackoverflow.com
How can I implement a keyboard interrupt in a while loop to break it instantly regardless of the current execution stage?
Put your loop in a new process and when you hit the 'q' key kill the process: from multiprocessing import Process import keyboard import time def my_loop(): while True: print("a") time.sleep(3) if __name__ == '__main__': process = Process(target=my_loop) process.start() while process.is_alive(): if keyboard.is_pressed('q'): process.terminate() break More on reddit.com
🌐 r/learnpython
26
41
July 12, 2023
Signal handler is registered, but process still exits abruptly on Ctrl+C (implementing graceful shutdown)
According to the docs, Asyncio.run() registers SIGINT handler manually in order to not hang program. https://docs.python.org/3/library/asyncio-runner.html#asyncio.run Here is relevant fragment: When signal.SIGINT is raised by Ctrl-C, KeyboardInterrupt exception is raised in the main thread by default. However this doesn’t work with asyncio because it can interrupt asyncio internals and can hang the program from exiting. To mitigate this issue, asyncio handles signal.SIGINT as follows: asyncio.Runner.run() installs a custom signal.SIGINT handler before any user code is executed and removes it when exiting from the function. The Runner creates the main task for the passed coroutine for its execution. When signal.SIGINT is raised by Ctrl-C, the custom signal handler cancels the main task by calling asyncio.Task.cancel() which raises asyncio.CancelledError inside the main task. This causes the Python stack to unwind, try/except and try/finally blocks can be used for resource cleanup. After the main task is cancelled, asyncio.Runner.run() raises KeyboardInterrupt . A user could write a tight loop which cannot be interrupted by asyncio.Task.cancel() , in which case the second following Ctrl-C immediately raises the KeyboardInterrupt without cancelling the main task. So if you want to make your code resistant to sigint, you have to clear any signal handlers at the begining of your job: https://stackoverflow.com/questions/22916783/reset-python-sigint-to-default-signal-handler But that might be a little overcomplicated. It would be much easier to implement a job proccessor as a separate thread, without asyncio interference. More on reddit.com
🌐 r/learnpython
4
6
September 4, 2024
🌐
Readthedocs
pycopy.readthedocs.io › en › latest › reference › isr_rules.html
Writing interrupt handlers — Pycopy 3.6.1 documentation
The callback is also guaranteed to run at a time when the main program has completed any update of Python objects, so the callback will not encounter partially updated objects. Typical usage is to handle sensor hardware. The ISR acquires data from the hardware and enables it to issue a further interrupt. It then schedules a callback to process the data. Scheduled callbacks should comply with the principles of interrupt handler design outlined below.
🌐
Readthedocs
mpython.readthedocs.io › en › v2.2.1 › reference › isr_rules.html
Write interrupt handler — mPython board 2.2.2 documentation
On the appropriate hardware, MicroPython provides the ability to write interrupt handlers in Python. Interrupt handler-also known as interrupt service routine (ISR), defined as a callback function. These functions are all executed in response to events such as timer triggers or voltage changes ...
🌐
Python
docs.python.org › 3 › library › signal.html
signal — Set handlers for asynchronous events
This is another standard signal handler, which will simply ignore the given signal. ... Abort signal from abort(3). ... Timer signal from alarm(2). Availability: Unix. ... Interrupt from keyboard (CTRL + BREAK).
🌐
Super Fast Python
superfastpython.com › home › tutorials › interrupt the main thread in python
Interrupt the Main Thread in Python - Super Fast Python
September 12, 2022 - You can interrupt the main thread via the _thread.interrupt_main() function. In this tutorial you will discover how to interrupt the main thread from another thread in Python. Let’s get started. Need to Interrupt Main Thread A thread is a thread of execution in a computer program.
🌐
Adafruit
learn.adafruit.com › cooperative-multitasking-in-circuitpython-with-asyncio › handling-interrupts
Handling Interrupts | Cooperative Multitasking in CircuitPython with asyncio | Adafruit Learning System
November 24, 2021 - When an interrupt occurs, the interrupt mechanism will call a routine called an interrupt handler. The currently running program is temporarily suspended and other interrupts of lower priority are blocked.
🌐
Xanthium
xanthium.in › operating-system-signal-handling-in-python3
Capturing and Handling OS signals like SIGINT (CTRL-C) in Python | xanthium enterprises
October 18, 2023 - In those applications we can use the SIGINT signal (CTRL +C) to interrupt the infinite loop and close the application safely without a resource leak. You can also use a SIGBREAK (CTRL + BREAK ) signal to do so but the signal is only available in Windows while SIGINT is available on both Linux ...
Find elsewhere
🌐
Pyodide
pyodide.org › en › stable › usage › keyboard-interrupts.html
Interrupting execution — Version 0.29.3
To use the interrupt system, you should create a SharedArrayBuffer on either the main thread or the worker thread and share it with the other thread. You should use pyodide.setInterruptBuffer() to set the interrupt buffer on the Pyodide thread. When you want to indicate an interrupt, write ...
🌐
MicroPython
docs.micropython.org › en › v1.15 › reference › isr_rules.html
Writing interrupt handlers — MicroPython 1.15 documentation
On suitable hardware MicroPython offers the ability to write interrupt handlers in Python. Interrupt handlers - also known as interrupt service routines (ISR’s) - are defined as callback functions. These are executed in response to an event such as a timer trigger or a voltage change on a pin.
🌐
MicroPython
docs.micropython.org › en › v1.9.3 › pyboard › reference › isr_rules.html
Writing interrupt handlers — MicroPython 1.9.3 documentation
On suitable hardware MicroPython offers the ability to write interrupt handlers in Python. Interrupt handlers - also known as interrupt service routines (ISR’s) - are defined as callback functions. These are executed in response to an event such as a timer trigger or a voltage change on a pin.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-catch-a-keyboardinterrupt-in-python
How To Catch A Keyboardinterrupt in Python - GeeksforGeeks
July 23, 2025 - Press Ctrl+C to interrupt. Processing step 1 Processing step 2 Processing step 3 Processing step 4 Processing step 5 Exiting the program. Catching KeyboardInterrupt in Python is essential for handling user interruptions gracefully, especially ...
🌐
MicroPython
docs.micropython.org › en › v1.8.5 › wipy › reference › isr_rules.html
Writing interrupt handlers — MicroPython 1.8.5 documentation
On suitable hardware MicroPython offers the ability to write interrupt handlers in Python. Interrupt handlers - also known as interrupt service routines (ISR’s) - are defined as callback functions. These are executed in response to an event such as a timer trigger or a voltage change on a pin.
🌐
RasPi.TV
raspi.tv › 2013 › how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio
How to use interrupts with Python on the Raspberry Pi and RPi.GPIO – RasPi.TV
December 31, 2018 - The latest big news in the world of Raspberry Pi Python GPIO programming is that Ben Croston has released an update for RPi.GPIO. Why is that a big deal? Because this version has interrupts. &#8220…
Top answer
1 of 3
8

It's generally recommended not to use exception calling for flow-control. Instead, look to python stdlib's threading.Event, even if you only plan on using a single thread (even the most basic Python program uses at least one thread).

This answer https://stackoverflow.com/a/46346184/914778 has a good explanation of how calling one function (function b) could interrupt another (function a).

Here's a few important parts, summarized from that other answer.

Set up your threading libraries:

from threading import Event
global exit
exit = Event()

This is a good replacement for time.sleep(60), as it can be interrupt:

exit.wait(60)

This code will execute, until you change exit to "set":

while not exit.is_set():
    do_a_thing()

This will cause exit.wait(60) to stop waiting, and exit.is_set() will return True:

exit.set()

This will enable execution again, and exit.is_set() will return False:

exit.clear()
2 of 3
5

I would do the following:

  • define a custom exception
  • call the callback function within an appropriate try/catch block
  • if the callback function decides to break the execution, it will raise exception and the caller will catch it and handle it as needed.

Here's some pseudo-code:

class InterruptExecution (Exception):
    pass

def function_a():
    while some_condition_is_true():
        do_something()
        if callback_time():
            try:
                function_b()
            except InterruptExecution:
                break
        do_something_else()
    do_final_stuff()


def function_b():
    do_this_and_that()
    if interruption_needed():
        raise (InterruptExecution('Stop the damn thing'))
🌐
Readthedocs
cysignals.readthedocs.io › en › latest › interrupt.html
Interrupt handling — cysignals 1.11.2a0.dev0 documentation
The code inside sig_on() should be pure C or Cython code. If you call any Python code or manipulate any Python object (even something trivial like x = []), an interrupt can mess up Python’s internal state.