【问题标题】:How to check if thread (from bunch of threads) threw an exception?如何检查线程(来自一堆线程)是否抛出异常?
【发布时间】:2020-07-24 13:13:37
【问题描述】:

我创建了一个运行多个线程的脚本。每个线程在无限循环中运行一个函数。我想知道是否有任何线程抛出异常。

这是线程启动的基本结构:

def main():
    VODP = Packager()
    WINSCP = WinSCP()
    threadList = []
    threadList.append(threading.Thread(target=VODP.scan))
    threadList.append(threading.Thread(target=WINSCP.ftp_sender))
    threadList.append(threading.Thread(target=WINSCP.ftp_status_checker))
    threadList.append(threading.Thread(target=WINSCP.synchronize))
    for thread in threadList:
        thread.start()
    for thread in threadList:
        thread.join()

main()

这是一个具有无限循环功能的类的示例:

class Packager:
    def __init__(self):
        self.rootDir, self.scanTime, self.extendedScanTime = self.configure_packager()
        self.foldersReadyToPack = []
    def scan(self):
        while True:
            if self.foldersReadyToPack == []:
                for dirpath, dirnames, filenames in os.walk(self.rootDir):
                    if(folder_verifier(dirpath)):
                        #print("Currently scanned folder: ", dirpath)
                        package_creator(dirpath)
                if len(self.foldersReadyToPack) > 0:
                    #print(f'Folders with suitable files has been found!')
                    packingQueue = PackingQueue(self.foldersReadyToPack)
                    packingQueue.execute_packing()
                    self.foldersReadyToPack = packingQueue.elements

我怎样才能做到这一点?如何获取线程抛出异常并且不再无限循环执行其任务的信息?当程序中发生可疑情况时,我希望将此类信息传递给负责发送电子邮件的班级。

【问题讨论】:

  • 请看一下这个主题,你可能会发现它很有帮助,因为有很多方法可以从线程中获取结果:stackoverflow.com/questions/6893968/…(我建议看一下@987654324 @)。

标签: python multithreading exception


【解决方案1】:

你可以使用concurrent.futures:

import concurrent.futures


def foo_with_exc(a, b):
    raise ValueError()


def thread_starter():
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        future = executor.submit(foo_with_exc, 1, 2)

        # Raise any exceptions raised by thread
        return future.result()


try:
    thread_starter()
except ValueError as e:
    print("Exception!")

【讨论】:

  • 所以在我的情况下,由于foo_with_exc 功能无限重复,我应该将try 语句放在while Trueexcept 语句之前引发错误?或者我应该在启动/加入线程期间放置它?
猜你喜欢
  • 2013-08-23
  • 1970-01-01
  • 2022-09-28
  • 2018-09-18
  • 1970-01-01
  • 1970-01-01
  • 2014-04-03
  • 1970-01-01
  • 2016-07-28
相关资源
最近更新 更多