如何在python中的线程之间传递异常 [英] How do I pass an exception between threads in python

查看:280
本文介绍了如何在python中的线程之间传递异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要跨线程边界传递异常.

I need to pass exceptions across a thread boundary.

我正在使用一个非线程安全应用程序中嵌入的python,该应用程序具有一个线程安全调用post_event(callable),该调用从其主线程调用callable.

I'm using python embedded in a non thread safe app which has one thread safe call, post_event(callable), which calls callable from its main thread.

我在单独的线程中运行pygtk gui,因此单击按钮时,我会使用post_event发布事件,并等待其完成后再继续.但是我需要调用者知道被调用者是否抛出异常,如果发生则引发异常.我不太担心回溯,只是异常本身.

I am running a pygtk gui in a seperate thread, so when a button is clicked I post an event with post_event, and wait for it to finish before continuing. But I need the caller to know if the callee threw an exception, and raise it if so. I'm not too worried about the traceback, just the exception itself.

我的代码大致是:

class Callback():
    def __init__(self,func,*args):
        self.func=func
        self.args=args
        self.event=threading.Event()
        self.result=None
        self.exception=None
    def __call__(self):
        gtk.gdk.threads_enter()
        try:
            self.result=self.func(*self.args)
        except:
            #what do I do here? How do I store the exception?
            pass
        finally:
            gtk.gdk.threads_leave()
            self.event.set()
    def post(self):
        post_event(self)
        gtk.gdk.threads_leave()
        self.event.wait()
        gtk.gdk.threads_enter()
        if self.exception:
            raise self.exception
        return self.result

任何帮助表示感谢,谢谢.

Any help appreciated, thanks.

推荐答案

#我在这里做什么?如何存储异常?

#what do I do here? How do I store the exception?

使用sys.exc_info()[:2],请参见此Wiki

在线程之间进行通信的最佳方法是队列.让主线程实例化一个Queue.Queue实例并将其传递给子线程;当子线程有一些要与主线程通信的东西时,它将在该队列上使用.put(例如,具有线程ID,异常类型,异常值的元组,或者其他有用的信息,不一定与异常相关),只需确保元组的第一项标识信息的种类;-).主机可以在需要时.get将这些信息单元返回,并具有各种同步选择等等.

Best way to communicate among threads is Queue. Have the main thread instantiate a Queue.Queue instance and pass it to subthreads; when a subthread has something to communicate back to the master it uses .put on that queue (e.g. a tuple with thread id, exception type, exception value -- or, other useful info, not necessarily exception-related, just make sure the first item of a tuple identifies the kind of info;-). The master can .get those info-units back when it wants, with various choices for synchronization and so on.

这篇关于如何在python中的线程之间传递异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆