[docs] [issue6634] sys.exit() called from threads other than the main one: undocumented behaviour

Jan-Philip Gehrcke report at bugs.python.org
Sat Sep 25 15:23:07 CEST 2010

Jan-Philip Gehrcke <jgehrcke at gmail.com> added the comment:

Sorry for the delay.

Before suggesting a doc change to correct/complete the description of the *current* situation, we actually should consider changing this situation. I think this is reasonable and I feel encouraged by Gabriel Genellina:

> I see no reason for sys.exit("msg") NOT to write to stderr
> inside a child thread.

This patch enables printing to stderr from child threads and clones the behavior of `sys.exit(arg)` called from the main thread:

--- C:/Python27/Lib/threading.py    Sat Apr 10 18:55:48 2010
+++ C:/python_sys_exit_issue/threading.py    Sat Sep 25 14:50:24 2010
@@ -531,6 +531,15 @@
 except SystemExit:
     if __debug__:
         self._note("%s.__bootstrap(): raised SystemExit", self)
+    # Now get and handle the "exit code", given by the user via
+    # the second expression after `raise` or via the argument of 
+    # sys.exit().
+    code = self.__exc_info()[1].code
+    # Ignore None and integer exit code. Print any other object
+    # to stderr as it is the behavior of sys.exit(arg) called
+    # from the main thread.
+    if code is not None and not isinstance(code, int):
+        _sys.stderr.write("%s\n" % code)
     if __debug__:
         self._note("%s.__bootstrap(): unhandled exception", self)

A script with different testcases including output is attached.

What do you think?

All the best,

Jan-Philip Gehrcke

Added file: http://bugs.python.org/file19006/thread_sys_exit_test.py

Python tracker <report at bugs.python.org>

More information about the docs mailing list