Use the atexit module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as KeyboardInterrupt
. Such termination functions may (though inevitably in the main thread!) call any stop
function you require; together with the possibility of setting a thread as daemon
, that gives you the tools to properly design the system functionality you need.