concurrent.futures.ThreadPoolExecutor 不打印错误 [英] concurrent.futures.ThreadPoolExecutor doesn't print errors

查看:93
本文介绍了concurrent.futures.ThreadPoolExecutor 不打印错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 concurrent.futures.ThreadPoolExecutor 模块并行运行类方法,我的代码的简化版本几乎如下:

class 测试类:def __init__(self, secondsToSleepFor):self.secondsToSleepFor = secondsToSleepFordef testMethodToExecInParallel(self):打印(线程名称:" + threading.currentThread().getName())print(threading.currentThread().getName() + " 正在睡眠 " + str(self.secondsToSleepFor) + " seconds")time.sleep(self.secondsToSleepFor)打印(threading.currentThread().getName()+已经完成!!")以 concurrent.futures.ThreadPoolExecutor(max_workers = 2) 作为执行者:期货列表 = []打印(尝试前")尝试:测试类 = 测试类(3)未来 = executor.submit(testClass.testMethodToExecInParallel)futuresList.append(未来)除了例外作为 exc:print('异常产生:%s' % exc)

如果我执行此代码,它似乎表现得像预期的那样.但是如果我犯了一个错误,比如在testMethodToExecInParallel"中指定了错误数量的参数,比如:

 def testMethodToExecInParallel(self, secondsToSleepFor):

然后仍然提交函数为:

future = executor.submit(testClass.testMethodToExecInParallel)

或尝试在testMethodToExecInParallel"方法的打印语句中将字符串对象与整数对象(不使用 str(.) )连接起来:

def testMethodToExecInParallel(self):打印(线程名称:" + threading.currentThread().getName())print("self.secondsToSleepFor: " + self.secondsToSleepFor) <-- 应该在这里报告错误

程序没有返回任何错误;只打印before try"并结束执行...

很容易理解这使得程序几乎无法调试......有人可以解释我为什么会发生这种行为吗?

(对于第一种错误情况) concurrent.futures.ThreadPoolExecutor 不检查具有指定签名的函数来提交,并最终抛出某种noSuchFunction"异常?

也许在提交给 ThreadPoolExecutor 类方法而不是简单的独立函数时存在某种问题,因此,这种行为是否可以预期?

或者错误是在线程内部抛出的,由于某种原因我无法读取它?

-- 编辑 --

Akshay.N 建议在将函数提交给 ThreadPoolExecutor 后插入 future.result() 使程序按预期运行:如果代码正确,则运行良好,如果代码中的某些内容错误,则打印错误.

我认为必须警告用户注意 ThreadPoolExecutor 的这种非常奇怪的行为:如果您只向 ThreadPoolExecutor 不调用 future.result() 提交函数:- 如果代码正确,程序继续运行并按预期运行- 如果代码中出现错误,程序似乎不会调用提交的函数,无论它做什么:它不会报告代码中的错误

解决方案

据我所知,目前还没有",你必须在executor.submit(testClass.testMethodToExecInParallel)"以执行线程池.我已经试过了你说的,它给了我错误,下面是代码

<预><代码>>>>导入 concurrent.futures 作为 cf>>>executor = cf.ThreadPoolExecutor(1)>>>定义 a(x,y):...打印(x+y)...>>>未来 = executor.submit(a, 2, 35, 45)>>>未来结果()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件C:\用户\用户名\AppData\Local\Programs\Python\Python37\lib\concurrent\futures\_base.py",行425,结果返回 self.__get_result()文件C:\用户\用户名\AppData\Local\Programs\Python\Python37\lib\concurrent\futures\_base.py",行第384话引发 self._exception文件C:\用户\用户名\AppData\Local\Programs\Python\Python37\lib\concurrent\futures\thread.py",行57、运行中结果 = self.fn(*self.args, **self.kwargs)类型错误:a() 需要 2 个位置参数,但给出了 3 个

如果它仍然不起作用,请告诉我

I am trying to use concurrent.futures.ThreadPoolExecutor module to run a class method in parallel, the simplified version of my code is pretty much the following:

class TestClass:

    def __init__(self, secondsToSleepFor):

        self.secondsToSleepFor = secondsToSleepFor


    def testMethodToExecInParallel(self):

        print("ThreadName: " + threading.currentThread().getName())


        print(threading.currentThread().getName() + " is sleeping for " + str(self.secondsToSleepFor) + " seconds")


        time.sleep(self.secondsToSleepFor)


        print(threading.currentThread().getName() + " has finished!!")


with concurrent.futures.ThreadPoolExecutor(max_workers = 2) as executor:

    futuresList = []

    print("before try")

    try:

         testClass = TestClass(3)        

         future = executor.submit(testClass.testMethodToExecInParallel)

         futuresList.append(future)

    except Exception as exc:

         print('Exception generated: %s' % exc)

If I execute this code it seems to behave like it is intended to. But if I make a mistake like specifying a wrong number of parameters in "testMethodToExecInParallel" like:

 def testMethodToExecInParallel(self, secondsToSleepFor):

and then still submitting the function as:

future = executor.submit(testClass.testMethodToExecInParallel)

or trying to concatenate a string object with an integer object (without using str(.) ) inside a print statement in "testMethodToExecInParallel" method:

def testMethodToExecInParallel(self):

        print("ThreadName: " + threading.currentThread().getName())
        print("self.secondsToSleepFor: " + self.secondsToSleepFor) <-- Should report an Error here

the program doesn't return any error; just prints "before try" and ends execution...

Is trivial to understand that this makes the program nearly undebuggable... Could someone explain me why such behaviour happens?

(for the first case of mistake) concurrent.futures.ThreadPoolExecutor doesn't check for a function with the specified signature to submit and, eventually, throw some sort of "noSuchFunction" exception?

Maybe there is some sort of problem in submitting to ThreadPoolExecutor class methods instead of simple standalone functions and, so, such behaviour could be expected?

Or maybe the error is thrown inside the thread and for some reason I can't read it?

-- EDIT --

Akshay.N suggestion of inserting future.result() after submitting functions to ThreadPoolExecutor makes the program behave as expected: goes nice if the code is correct, prints the error if something in the code is wrong.

I thing users must be warned about this very strange behaviour of ThreadPoolExecutor: if you only submit functions to ThreadPoolExecutor WITHOUT THEN CALLING future.result(): - if the code is correct, the program goes on and behaves as expected - if something in the code is wrong seems the program doesn't call the submitted function, whatever it does: it doesn't report the errors in the code

解决方案

As far as my knowledge goes which is "not so far", you have to call "e.results()" after "executor.submit(testClass.testMethodToExecInParallel)" in order to execute the threadpool . I have tried what you said and it is giving me error, below is the code

>>> import concurrent.futures as cf
>>> executor = cf.ThreadPoolExecutor(1)
>>> def a(x,y):
...     print(x+y)
...
>>> future = executor.submit(a, 2, 35, 45)
>>> future.result()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\username 
\AppData\Local\Programs\Python\Python37\lib\concurrent\futures\_base.py", line 
425, in result
    return self.__get_result()
  File "C:\Users\username
\AppData\Local\Programs\Python\Python37\lib\concurrent\futures\_base.py", line 
384, in __get_result
    raise self._exception
  File "C:\Users\username
\AppData\Local\Programs\Python\Python37\lib\concurrent\futures\thread.py", line 
57, in run
    result = self.fn(*self.args, **self.kwargs)
TypeError: a() takes 2 positional arguments but 3 were given

Let me know if it still doesn't work

这篇关于concurrent.futures.ThreadPoolExecutor 不打印错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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