Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从多个线程捕获异常?_Python_Python 3.x_Multithreading_Exception_Python Multithreading - Fatal编程技术网

Python 如何从多个线程捕获异常?

Python 如何从多个线程捕获异常?,python,python-3.x,multithreading,exception,python-multithreading,Python,Python 3.x,Multithreading,Exception,Python Multithreading,我有一组我想在线程中执行的函数。其中一些函数可能会引发我想要捕获的特定异常,分别针对每个线程 我尝试了一些类似的方法 导入线程 类MyException(异常): 通过 def fun(): 引起我的反感 myfuns=[threading.Thread(target=fun),threading.Thread(target=fun)] 对于myfuns中的myfun: 尝试: myfun.start() 除了我的例外: 打印(“捕获我的异常”) 我希望看到捕获MyException两次,每个

我有一组我想在线程中执行的函数。其中一些函数可能会引发我想要捕获的特定异常,分别针对每个线程

我尝试了一些类似的方法

导入线程
类MyException(异常):
通过
def fun():
引起我的反感
myfuns=[threading.Thread(target=fun),threading.Thread(target=fun)]
对于myfuns中的myfun:
尝试:
myfun.start()
除了我的例外:
打印(“捕获我的异常”)
我希望看到
捕获MyException
两次,每个线程一次。但只有一个


是否可以在线程中捕获彼此独立的异常?(换句话说:当线程引发异常时,请在调用该线程的代码中对其进行管理?

对于Python 3.8+,您可以为未捕获的异常定义一个处理程序

import threading

def f(args):
    print(f'caught {args.exc_type} with value {args.exc_value} in thread {args.thread}\n')
    
threading.excepthook = f

class MyException(Exception):
    pass

def fun():
    raise MyException

myfuns = [threading.Thread(target=fun), threading.Thread(target=fun)]
for myfun in myfuns:
    myfun.start()
for myfun in myfuns:
    myfun.join()

Python的哪个版本?@Woj:足够了?您在设计/实现方面是否足够早,可以用concurrent.futures进行重构?@wwii:Python 3.8。我在设计阶段。我当前的(业余/家庭)代码按顺序调用函数,我想对它们执行线程。我不知道concurrent.futures,因此我将阅读文档以了解这是如何实现的help@MauriceMeyer:这可能是一个非常有趣的解决方案-我将阅读详细信息并尝试一下,谢谢。谢谢-您的另一个
concurrent.futures
提案似乎有我的确切问题,例如: