Why monitoring keyboard interruption in python thread is not working

I have very simple python code:

def monitor_keyboard_interrupt(): is_done = False while True: if is_done break try: print(sys._getframe().f_code.co_name) except KeyboardInterrupt: is_done = True def test(): monitor_keyboard_thread = threading.Thread(target = monitor_keyboard_interrupt) monitor_keyboard_thread.start() monitor_keyboard_thread.join() def main(): test() if '__main__' == __name__: main() 

However, when I press 'Ctrl-C', the stream does not stop. Can someone explain what I'm doing wrong. Any help is appreciated.

+5
source share
1 answer

Simple reason:

Because only <_MainThread(MainThread, started 139712048375552)> can create signal handlers and listen to signals.

This includes KeyboardInterrupt , which is a SIGINT.

This comes directly from signal docs:

Caution should be exercised if both signals and streams are used in the same program. The main thing to remember when using signals and threads at the same time: they always perform signal () operations on the main execution thread. Any thread can execute an alarm (), getsignal (), pause (), setitimer () or getitimer (); only the main thread can install a new signal handler, and the main thread will be the only one for receiving signals (this is provided by the Python signal module, even if the implementation of the main thread supports sending signals to separate streams). This means that signals cannot be used as a means of cross-thread communication. Use locks instead.

+3
source

All Articles