Python daemon thread print exception

Python does not print trace messages from exceptions that occur in daemon threads.

For example, this code creates a daemon thread and throws an exception in a new thread:

def error_raiser(): raise Exception import threading thread = threading.Thread(target=error_raiser) thread.daemon = True thread.start() 

but does not print a trace. (He gives no way out).

However, if the thread is not specified as a daemon thread, Python will print a trace. Here is the same code with one line:

 def error_raiser(): raise Exception import threading thread = threading.Thread(target=error_raiser) # thread.daemon = True thread.start() 

and conclusion:

 Exception in Thread-1: Traceback (most recent call last): File "C:\Python26\lib\threading.py", line 525, in __bootstrap_inner self.run() File "C:\Python26\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File "test.py", line 2, in error_raiser raise Exception Exception 

Executing this code in both Python 2.6.2 and Python 3.0.1 yields the same results. It is interesting, however, that if I executed the code by importing it into the IPython shell, an exception would be displayed whether the stream is demonic or not.

According to the documentation, the only value of the daemon flag is that "the entire Python program terminates when only daemon threads remain." This would make me believe that not tracing after an exception is a bug in Python if I didn't miss something in the documentation.

Is this a mistake, or am I missing something in the documentation and is this behavior intentional? If this is intentional, how can I get Python to print the trace in daemon threads without using IPython?

+7
python multithreading
source share
1 answer

According to Wikipedia, by definition, the daemon should be separated from the control tty, so I think it is correct that the exception is not displayed (and in the end, the daemon should continue to work even if you close the shell that launched it) ..
See here .

Regarding how to print the trace, I think a simple try / except_then_log_to_file would do the trick :)

+6
source share

All Articles