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

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

问题描述

总的来说,我对 Python 和多线程编程非常陌生.基本上,我有一个脚本可以将文件复制到另一个位置.我希望将其放置在另一个线程中,以便我可以输出 .... 以指示脚本仍在运行.

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"

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

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.

线程类的代码如下:

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

推荐答案

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

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.

试试这个尺寸:

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()

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

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