Why does sys.exit() not exit when called inside a thread in Python?
What if I did want to exit the program from the thread?
Apart from the method Deestan described you can call os._exit
(notice the underscore). Before using it make sure that you understand that it does no cleanups (like calling __del__
or similar).
sys.exit()
raises the SystemExit
exception, as does thread.exit()
. So, when sys.exit()
raises that exception inside that thread, it has the same effect as calling thread.exit()
, which is why only the thread exits.
What if I did want to exit the program from the thread?
For Linux:
os.kill(os.getpid(), signal.SIGINT)
This sends a SIGINT
to the main thread which raises a KeyboardInterrupt
. With that you have a proper cleanup. Also you can register a handler, if you want to react differently.
For Windows:
The above does not work on Windows, as you can only send a SIGTERM
signal, which is not handled by Python and has the same effect as os._exit()
.
It only option is to use:
os._exit()
This will exit the entire process without any cleanup. If you need cleanup, you need to communicate with the main thread in another way.