python - 'sys.excepthook' 和线程

标签 python multithreading exception exception-handling

我正在使用 Python 2.5 并尝试在我的程序中使用自定义的 excepthook。在主线程中它工作得很好。但是在使用线程模块启动的线程中,通常的 excepthook 会被调用。

这是一个显示问题的例子。取消注释显示所需的行为。

import threading, sys

def myexcepthook(type, value, tb):
    print 'myexcepthook'

class A(threading.Thread, object):

    def __init__(self):
        threading.Thread.__init__(self, verbose=True)
#       raise Exception('in main')
        self.start()

    def run(self):
        print 'A'
        raise Exception('in thread')            

if __name__ == "__main__":
    sys.excepthook = myexcepthook
    A()

那么,如何在线程中使用我自己的excepthook

最佳答案

看起来这个错误仍然存​​在于(至少)3.4 中,Nadia Alramli 链接的讨论中的解决方法之一似乎也适用于 Python 3.4。

为了方便和记录,我将在此处发布(在我看来)最佳解决方法的代码。我稍微更新了编码风格和注释,使其更符合 PEP8 和 Pythonic。

import sys
import threading

def setup_thread_excepthook():
    """
    Workaround for `sys.excepthook` thread bug from:
    http://bugs.python.org/issue1230540

    Call once from the main thread before creating any threads.
    """

    init_original = threading.Thread.__init__

    def init(self, *args, **kwargs):

        init_original(self, *args, **kwargs)
        run_original = self.run

        def run_with_except_hook(*args2, **kwargs2):
            try:
                run_original(*args2, **kwargs2)
            except Exception:
                sys.excepthook(*sys.exc_info())

        self.run = run_with_except_hook

    threading.Thread.__init__ = init

关于python - 'sys.excepthook' 和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1643327/

相关文章:

python - 如何强制退出 Python 中的 CLOSE_WAIT 套接字?

python - 在 Python 中对文件内容进行排序

具有可抢占线程队列的java执行器

c++ - std::packaged_task<T> 的分配器构造函数

exception - 在 MFC 应用程序中,将最顶层的 try/catch 放在哪里?

java - 插入 TreeSet 时出现 ClassCastException

python - 尝试通过selenium python选择输入框,但每次重新加载页面时元素中的 'id'都会发生变化

python - 如何在 CNN 中为 AI 考勤添加新类别

java - vert.x 和 BIO 线程

java - 数据库try-catch block 代码不执行