相关疑难解决方法(0)

'sys.excepthook'和线程

我正在使用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()
Run Code Online (Sandbox Code Playgroud)

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

python multithreading exception-handling exception

18
推荐指数
3
解决办法
5587
查看次数

多进程上的 Python sys.excepthook

我正在尝试sys.excepthook在多进程上设置自定义。但它不起作用。

在下面的代码中,我希望将This is my traceback function:字符串打印为错误消息的前缀,但事实并非如此。

代码:

from multiprocessing import Process
import time
import traceback
import logging
import sys

def excepthook(etype, evalue, traceback):
    traceback_strs = traceback.format_exception_only(etype, evalue)
    exception_str = "This is my traceback function:" + "\r\n".join(traceback_strs)
    print("ExceptHook")
    print(exception_str)


def subprocess_main():
    sys.excepthook = excepthook
    time.sleep(3)
    raise Exception("HelloWorld")


if __name__ == "__main__":
    p = Process(target=subprocess_main)
    p.start()
    p.join()
Run Code Online (Sandbox Code Playgroud)

为什么它不起作用?

操作系统:Windows10
Python:3.6.3

python error-handling python-3.x

7
推荐指数
1
解决办法
1174
查看次数