3

Can you write interrupts in python which can trigger and break program flow as a result of some external event?

In particular suppose you have a thread doing a computation, you want that computation to break and divert program flow to some function if an external event happens. It could complete the operation of the current line but afterward program flow should be directed to another python function.

FourierFlux
  • 439
  • 5
  • 13
  • Yes, check out the `signal` [module docs](https://docs.python.org/3/library/signal.html) in the stdlib. – Michael Ruth Apr 24 '21 at 06:46
  • It's an old answer for Py 2.7 but might still be relevant https://stackoverflow.com/questions/23170318/real-time-interrupts-in-python – Klemen Tusar Apr 24 '21 at 06:46
  • Some more about interrupt and event management using examples of different modules: https://stackoverflow.com/questions/1092531/event-system-in-python https://stackoverflow.com/questions/25029537/interrupt-function-execution-from-another-function-in-python – IODEV Apr 24 '21 at 06:54
  • Interesting, is there a way to re-start program flow where you left off like in microcontrollers? – FourierFlux Apr 24 '21 at 23:02

1 Answers1

0

Python is based on the C language so many of its features are also available in Python (Some libraries are actually written in C and compiled for Python). You can look at signal for signals and interrupts

Tamir
  • 1,224
  • 1
  • 5
  • 18
  • 1
    Be aware that signal () is dependent on implementation, thus might behave completely differently depending on platform. Also, Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread. This means that signals can’t be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead. – IODEV Apr 24 '21 at 10:18