如何在Python3中检测concurrent.futures中的异常?

9 python multiprocessing python-2.7 python-3.4 concurrent.futures

由于其并发期货模块,我刚刚转到python3.我想知道我是否可以让它来检测错误.我想将并发期货用于并行程序,如果有更高效的模块请告诉我.

我不喜欢多处理,因为它太复杂,没有太多的文档.然而,如果有人可以编写一个没有类的Hello World,那么将使用多处理来并行计算,这样很容易理解.

这是一个简单的脚本:

from concurrent.futures import ThreadPoolExecutor

def pri():
    print("Hello World!!!")

def start():
    try:
        while True:
            pri()
    except KeyBoardInterrupt:
        print("YOU PRESSED CTRL+C")


with ThreadPoolExecutor(max_workers=3) as exe:
    exe.submit(start)
Run Code Online (Sandbox Code Playgroud)

上面的代码只是一个演示,关于CTRL + C如何无法打印satement.

我想要的是能够调用函数是一个错误存在.此错误检测必须来自函数本身.

另一个例子

import socket
from concurrent.futures import ThreadPoolExecutor 
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def con():
    try:
        s.connect((x,y))
        main()
    except: socket.gaierror
         err()
def err():
    time.sleep(1)
    con()
def main():
    s.send("[+] Hello")
with ThreadPoolExecutor as exe:
    exe.submit(con)
Run Code Online (Sandbox Code Playgroud)

Han*_*man 10

参加聚会太晚了,但也许它会帮助其他人......

我很确定最初的问题并没有得到真正的回答。人们对 user5327424 正在使用键盘中断引发异常的事实感到困惑,而重点是未引发异常(无论它是如何引起的)。例如:

import concurrent.futures


def main():
    numbers = range(10)

    with concurrent.futures.ThreadPoolExecutor() as executor:
        results = {executor.submit(raise_my_exception, number): number for number in numbers}


def raise_my_exception(number):
    print('Proof that this function is getting called. %s' % number)
    raise Exception('This never sees the light of day...')


main()
Run Code Online (Sandbox Code Playgroud)

执行上面的示例代码时,您将看到屏幕上显示的打印语句内的文本,但您永远不会看到异常。这是因为每个线程的结果都保存在results对象中。您需要迭代该对象以获取异常。以下示例显示了如何访问结果。

import concurrent.futures


def main():
    numbers = range(10)

    with concurrent.futures.ThreadPoolExecutor() as executor:
        results = {executor.submit(raise_my_exception, number): number for number in numbers}

    for result in results:
        # This will cause the exception to be raised (but only the first one)
        print(result.result())


def raise_my_exception(number):
    print('Proof that this function is getting called. %s' % number)
    raise Exception('This will be raised once the results are iterated.')


main()
Run Code Online (Sandbox Code Playgroud)

我不确定我是否喜欢这种行为,但它确实允许线程完全执行,而不管各个线程内部遇到的异常。


lai*_*e9m 4

是一个解决方案。我不确定你是否喜欢它,但我想不出其他的。我已经修改了您的代码以使其正常工作。

from concurrent.futures import ThreadPoolExecutor
import time

quit = False

def pri():
    print("Hello World!!!")

def start():
    while quit is not True:
        time.sleep(1)
        pri()

try:
    pool = ThreadPoolExecutor(max_workers=3)
    pool.submit(start)

    while quit is not True:
        print("hei")
        time.sleep(1)
except KeyboardInterrupt:
    quit = True
Run Code Online (Sandbox Code Playgroud)

以下是要点:

  1. 当您使用 时with ThreadPoolExecutor(max_workers=3) as exe,它会等待所有任务完成。看看医生

    如果wait为 True,则在所有待处理的 future 执行完毕并且与执行器关联的资源已被释放之前,此方法将不会返回。如果 wait 是False,则此方法将立即返回,并且当所有待处理的 future 执行完成时,与执行器关联的资源将被释放。无论 wait 的值是多少,在所有待处理的 future 执行完毕之前,整个 Python 程序都不会退出。

    如果使用该语句,您可以避免必须显式调用此方法with,这将关闭Executor(等待就像在Executor.shutdown()wait 设置为 的情况下调用一样True

    这就像调用join()一个线程。
    这就是为什么我将其替换为:

    pool = ThreadPoolExecutor(max_workers=3)
    pool.submit(start)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 主线程必须正在“工作”才能捕获 Ctrl+C。所以你不能只是将主线程留在那里然后退出,最简单的方法是运行无限循环

  3. 现在您已经在主线程中运行了一个循环,当您点击 时CTRL+C,程序将进入except KeyboardInterrupt块并设置quit=True。然后你的工作线程就可以退出了。

严格来说,这只是一种解决方法。在我看来,不可能有其他方法来解决这个问题。

编辑
我不确定是什么困扰着你,但你可以毫无问题地捕获另一个线程中的异常:

import socket
import time
from concurrent.futures import ThreadPoolExecutor 
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

def con():
    try:
        raise socket.gaierror
        main()
    except socket.gaierror:
        print("gaierror occurred")
        err()

def err():
    print("err invoked")
    time.sleep(1)
    con()

def main():
    s.send("[+] Hello")

with ThreadPoolExecutor(3) as exe:
    exe.submit(con)
Run Code Online (Sandbox Code Playgroud)

输出

gaierror occurred
err invoked
gaierror occurred
err invoked
gaierror occurred
err invoked
gaierror occurred
...
Run Code Online (Sandbox Code Playgroud)