在Python中打印守护线程异常

在Python中打印守护线程异常

本文介绍了在Python中打印守护线程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python不会从守护程序线程中引发的异常中打印回溯消息.

Python does not print traceback messages from exceptions raised in daemon threads.

例如,此代码创建一个守护线程并在新线程中引发异常:

For example, this code creates a daemonic thread and raises an exception in the 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 traceback. (It gives no output).

但是,如果未将线程设置为守护程序线程,Python将打印回溯.这是同一行代码,其中一行被注释掉了:

However, if the thread is not set as a daemon thread, Python will print the traceback. Here is the same code with one line commented out:

def error_raiser():
    raise Exception

import threading
thread = threading.Thread(target=error_raiser)
# thread.daemon = True
thread.start()

和输出:

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

在Python 2.6.2和Python 3.0.1中执行此代码,并得到相同的结果.但是,有趣的是,如果我通过将代码导入IPython shell中来执行代码,则无论线程是否为守护程序,都会显示异常.

Executing this code in both Python 2.6.2 and Python 3.0.1 and gives the same results. Interestingly, however, if I execute the code by importing it in the IPython shell, the exception is displayed whether the thread is daemonic or not.

根据文档,"daemon"标志的唯一含义是仅保留守护程序线程时,整个Python程序都会退出".这会让我相信,除非我错过了文档中的内容,否则异常后不打印回溯是Python中的错误.

According to the documentation, the only significance of the 'daemon' flag is that "the entire Python program exits when only daemon threads are left." This would make me believe that not printing a traceback after an exception is a bug in Python, unless I missed something in the documentation.

这是一个错误,还是我错过了文档中的某些内容,并且此行为是故意的?如果是故意的,我该如何强制Python在不使用IPython的情况下在后台驻留程序线程中打印回溯?

Is this a bug, or did I miss something in the documentation and this behavior is intentional? If it is intentional, how can I force Python to print the traceback in daemon threads without using IPython?

推荐答案

根据Wikipedia,根据定义,守护程序应将其自身与控制tty分离,因此我认为没有任何异常显示是正确的(毕竟,守护程序是这样)即使关闭启动它的外壳,它也应该继续工作.)
请参见此处.

According to Wikipedia, by definition a daemon should detach itself from the controlling tty, so I think it's correct that no exception is shown (and after all, a daemon should keep working even if you close the shell that launched it)..
See here.

关于如何打印回溯,我认为一个简单的try/except_then_log_to_file可以解决问题:)

As for how to print the traceback, I think that a simple try/except_then_log_to_file would do the trick :)

这篇关于在Python中打印守护线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:59