Search code examples
pythonmultithreading

How to exit the entire application from a Python thread?


How can I exit my entire Python application from one of its threads? sys.exit() only terminates the thread in which it is called, so that is no help.

I would not like to use an os.kill() solution, as this isn't very clean.


Solution

  • If all your threads except the main ones are daemons, the best approach is generally thread.interrupt_main() -- any thread can use it to raise a KeyboardInterrupt in the main thread, which can normally lead to reasonably clean exit from the main thread (including finalizers in the main thread getting called, etc).

    Of course, if this results in some non-daemon thread keeping the whole process alive, you need to followup with os._exit as Mark recommends -- but I'd see that as the last resort (kind of like a kill -9;-) because it terminates things quite brusquely (finalizers not run, including try/finally blocks, with blocks, atexit functions, etc).