Skip to content
Advertisement

In Python code below, how can I immediately exit the code?

I have been trying below this two days, but cannot make it work.

I have tried

JavaScript

, and so on.

I have tried the code, but it terminates only after 30 seconds or 1 minute. It seems like “listener” in the code makes the code complicated.

I need to make the code terminate immediately when I press ESC. “Terminate” here means stop the code from running or close the entire terminal. Either way is fine, but it needs to work “immediately”.

I am using Windows10. It does not need to be compatible with MAC os.

JavaScript

Advertisement

Answer

The program won’t exit while the click_thread is still running. If the clicker knows that it’s supposed to exit it can break the loop and return. Alternatively, if you mark the thread as a daemon:

JavaScript

then it will exit when the main program exits.

You can test this with the tiny program below. Try with daemon=True and with daemon=None:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement