Threading Keyboard Interrupt issue
That's a little weird, and my running it works slightly differently. Please paste exactly what you're running (no time import and true being lowercase for example means we couldn't copy and paste it and have it immediately run)
In your script, the main thread hits y.start() which completes successfully as soon as the new thread gets going, so it exits the try/except block as a success. Then since there's no more code, the main thread completes.
The loop thread you started inherits the daemon-ness of the thread that called it, so by default it's started as a regular thread, and not a daemon thread. As a regular thread it will keep going even when the main thread completes.
Keyboard interrupts are only received by the main thread, which in this case completes real quick.
So what happens for me is that the main thread runs to completion instantly and leaves nothing alive to receive the keyboard interrupt, which means the loop thread will run forever until killed externally. (Task manager, ctrl-break, etc)
In this case, even if the main thread _was_ still alive to catch the keyboard interrupt, that exception does not get automatically passed to all threads, only the main one. So the main thread would have to catch the exception, then use one of the available signaling mechanisms to let the other threads know, and each of those other threads would have to consciously check for your signal of choice to see if the main thread wanted them to shut down.
Or, the other threads would have to be declared as demonic before they were started, in which case they would be killed automatically once all non-daemonic threads had ended.
From: Python-list [mailto:python-list-bounces+david.raymond=tomtom.com at python.org] On Behalf Of nihar Modi
Sent: Wednesday, May 29, 2019 4:39 AM
To: python-list at python.org
Subject: Threading Keyboard Interrupt issue
I have written a simple code that involves threading, but it does not go to
except clause after Keyboard interrupt. Can you suggest a way out. I have
pasted the code below. It does not print 'hi' after keyboard interrupt and
if __name__ == '__main__':
y = threading.Thread(target = loop, args = ())
The program does not print hi and terminates immediately after ctrl+c