在Python中的调用者线程中捕获一个线程的异常 [英] Catch a thread's exception in the caller thread in Python

查看:842
本文介绍了在Python中的调用者线程中捕获一个线程的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,我对Python和多线程编程非常新鲜。基本上,我有一个脚本将文件复制到另一个位置。我想把它放在另一个线程中,所以我可以输出 .... 来表示脚本仍在运行。



我遇到的问题是,如果文件无法复制,它将抛出异常。如果在主线程中运行,这是可以的但是,有以下代码不起作用:

  try:
threadClass = TheThread(param1,param2等) )
threadClass.start()##### **异常发生在这里**
除了:
打印捕获异常

在线程类本身,我尝试重新抛出异常,但它不起作用。我看到有人在这里提出类似的问题,但他们似乎都在做比我想要做的更具体的事情(而且我不太了解所提供的解决方案)。我看到人们提到使用 sys.exc_info(),但是我不知道在哪里或如何使用它。



所有的帮助非常感谢!



编辑:线程类的代码如下:

 类TheThread(threading.Thread):
def __init __(self,sourceFolder,destFolder):
threading.Thread .__ init __ )
self.sourceFolder = sourceFolder
self.destFolder = destFolder

def run(self):
try:
shul.copytree(self.sourceFolder ,self.destFolder)
除了:
raise


解决方案

问题是, thread_obj.start()立即返回。您生成的子线程在自己的上下文中执行,并使用自己的堆栈。发生在那里的任何异常都是在子线程的上下文中,并且它在它自己的堆栈中。现在我可以想到的一种方法是将这些信息传达给父线程,就是使用某种消息传递,所以你可以看看。



大小:

 导入sys 
导入线程
导入队列


class ExcThread(threading.Thread):

def __init __(self,bucket):
threading.Thread .__ init __(self)
self.bucket = bucket

def run(self):
try:
raise异常('这里发生错误')
除了异常:
self.bucket.put sys.exc_info())


def main():
bucket = Queue.Queue()
thread_obj = ExcThread(bucket)
thread_obj。 start()

while True:
try:
exc = bucket.get(block = False)
除了Queue.Empty:
pass
else:
exc_type,exc_obj,exc_trace = exc
#处理异常
打印exc_type,exc_obj
打印exc_trace

thread_obj.join(0.1)
如果thread_obj.isAlive():
continue
else:
break


如果__name__ =='__main__':
main()


I'm very new to Python and multithreaded programming in general. Basically, I have a script that will copy files to another location. I would like this to be placed in another thread so I can output .... to indicate that the script is still running.

The problem that I am having is that if the files cannot be copied it will throw an exception. This is ok if running in the main thread; however, having the following code does not work:

try:
    threadClass = TheThread(param1, param2, etc.)
    threadClass.start()   ##### **Exception takes place here**
except:
    print "Caught an exception"

In the thread class itself, I tried to re-throw the exception, but it does not work. I have seen people on here ask similar questions, but they all seem to be doing something more specific than what I am trying to do (and I don't quite understand the solutions offered). I have seen people mention the usage of sys.exc_info(), however I do not know where or how to use it.

All help is greatly appreciated!

EDIT: The code for the thread class is below:

class TheThread(threading.Thread):
    def __init__(self, sourceFolder, destFolder):
        threading.Thread.__init__(self)
        self.sourceFolder = sourceFolder
        self.destFolder = destFolder

    def run(self):
        try:
           shul.copytree(self.sourceFolder, self.destFolder)
        except:
           raise

解决方案

The problem is that thread_obj.start() returns immediately. The child thread that you spawned executes in its own context, with its own stack. Any exception that occurs there is in the context of the child thread, and it is in its own stack. One way I can think of right now to communicate this information to the parent thread is by using some sort of message passing, so you might look into that.

Try this on for size:

import sys
import threading
import Queue


class ExcThread(threading.Thread):

    def __init__(self, bucket):
        threading.Thread.__init__(self)
        self.bucket = bucket

    def run(self):
        try:
            raise Exception('An error occured here.')
        except Exception:
            self.bucket.put(sys.exc_info())


def main():
    bucket = Queue.Queue()
    thread_obj = ExcThread(bucket)
    thread_obj.start()

    while True:
        try:
            exc = bucket.get(block=False)
        except Queue.Empty:
            pass
        else:
            exc_type, exc_obj, exc_trace = exc
            # deal with the exception
            print exc_type, exc_obj
            print exc_trace

        thread_obj.join(0.1)
        if thread_obj.isAlive():
            continue
        else:
            break


if __name__ == '__main__':
    main()

这篇关于在Python中的调用者线程中捕获一个线程的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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