Python: Why does `sys.exit(msg)` called from a thread not print `msg` to stderr? Python: Why does `sys.exit(msg)` called from a thread not print `msg` to stderr? multithreading multithreading

Python: Why does `sys.exit(msg)` called from a thread not print `msg` to stderr?


I agree that the Python docs are incorrect, or maybe more precisely incomplete, regarding sys.exit and SystemExit when called/raised by threads other than the main one; please open a doc issue on the Python online tracker so this can be addressed in a future iteration of the docs (probably a near-future one -- doc fixes are easier and smoother than code fixes;-).

The remedy is pretty easy, of course -- just wrap any function you're using as the target of a threading.Thread with a decorator that does a try/except SystemExit, e: around it, and performs the "write to stderr" extra functionality you require (or, maybe better, uses a logging.error call instead) before terminating. But, with the doc issue that you correctly point out, it's hard to think about doing that unless and until one has met with the problem and in fact has had to spend some time in debugging to pin it down, as you've had to do (on the collective behalf of the core python developers -- sorry!).


Not all threads in python are equal. Calling sys.exit from a thread, does not actually exit the system. Thus, calling sys.exit() from a child thread is nonsensical, so it makes sense that it does not behave the way you expect.

This page talks more about threading objects, and the differences between threads and the special "main" thread.