Python 无法使用上下文管理器从线程捕获异常
目标脚本Python 无法使用上下文管理器从线程捕获异常,python,multithreading,exception,contextmanager,Python,Multithreading,Exception,Contextmanager,目标脚本 from threading import Thread import instrument import sys args=None def main(): function1() def function1(): with open("help11.txt") as f: print(f.read()) if __name__ == "__main__": with instrument
from threading import Thread
import instrument
import sys
args=None
def main():
function1()
def function1():
with open("help11.txt") as f:
print(f.read())
if __name__ == "__main__":
with instrument.FooManager():
t= Thread(target=main)
t.start()
t.join()
上下文管理器定义工具.py
class FooManager(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
def __enter__(self):
self.start_time, self.fmt_start_time = self.__timings()
def __exit__(self, exc_type, exc_value, traceback):
print(exc_type)
print(exc_value)
self.end_time, self.fmt_end_time = self.__timings()
duration = (self.end_time - self.start_time)
print("start_time",self.start_time)
print("end_time",self.end_time)
print("duration",duration)
def __timings(self):
return time.time(),time.strftime('%Y-%m-%d %H:%M %Z', time.gmtime(time.time()))
实际产量
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "test.py", line 10, in main
function1(10000000, 1)
File "test.py", line 14, in function1
with open("help11.txt") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'help11.txt'
None
None
fmt_start_time 1602782848.645685
end_time 1602782848.6461706
duration 0.0004856586456298828
预期产量
我想要的只是使用上下文管理器以某种方式捕获错误,而不是在exc_type和exc_value中获取值为None,或者,在上下文管理器中捕获线程引发的错误的推荐方法是什么
注意:当“with statement”之后没有线程声明时,此代码工作正常。要从线程传播异常,请使用
ThreadPoolExecutorfromconcurrent.futures
from concurrent.futures.thread import ThreadPoolExecutor
def foo():
raise RuntimeError()
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(foo)
print(future.result())
要从线程传播异常,请使用ThreadPoolExecutor
fromconcurrent.futures
from concurrent.futures.thread import ThreadPoolExecutor
def foo():
raise RuntimeError()
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(foo)
print(future.result())
线程未引发任何错误。正如标题“线程线程1中的异常:”所说,错误仅在线程内部。t.start()
和``t.join()``都不向调用线程提供线程t
的返回值或异常。你能改变线程负载的实现,或者线程是如何创建的吗?你能给我一个基于上面上下文的例子吗?线程没有引发错误。正如标题“线程线程1中的异常:”所说,错误仅在线程内部。t.start()
和``t.join()``都不向调用线程提供线程t
的返回值或异常。你能改变线程负载的实现,或者线程是如何创建的吗?你能给我一个基于上面上下文的例子吗