![](/img/trans.png)
[英]How to get the currentThread().getName() as part of (concurrent.futures) future result?
[英]How to get the name of the analyzed completed future in concurrent.futures?
在尋找我的問題的答案(鏈接副本中的一個答案中提供了一個解決方案)時,我發現了concurrent.futures
,特別是concurrent.futures.as_completed
。
我最終得到的代碼(對於上下文:我需要在主程序中捕獲從該主程序啟動的線程中引發的異常)工作正常,除了我不知道如何重新附加到 function 的名稱在concurrent.futures.as_completed
中被審查:
import concurrent.futures
class Checks:
@staticmethod
def isok():
print("OK")
@staticmethod
def isko():
raise Exception("KO")
# db will keep a map of method names in Check with the thread handler
db = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
# get the names of the methods in Check, discarding the built-ion ones
for check in [k for k in dir(Checks) if not k.startswith('_')]:
db[check] = executor.submit(getattr(Checks, check))
# at that point I have a map of function_name_as_a_string -> thread handler
for future in concurrent.futures.as_completed([db[k] for k in db.keys()]):
if future.exception():
print(f"{str(future.exception())} was raised (I do not know where, somewhere)")
else:
print("success (again, I do not know where, exactly)")
# all the threads are finished at that point
print("all threads are done")
在成功/失敗輸出中,我知道一個方法是否存在異常。 我不知道是誰做了什么。
由於迭代必須通過線程處理程序,我無法找到一種方法來“注入”循環中的方法名稱以在print()
中使用它 - 我該怎么做?
一種可能的解決方案是使用zip()
並創建 (name, handler) 元組的迭代器:
import concurrent.futures
class Checks:
@staticmethod
def isok():
print("OK")
@staticmethod
def isko():
raise Exception("KO")
# db will keep a map of method namles in Check with the actual (executable) method
db = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
for check in [k for k in dir(Checks) if not k.startswith('_')]:
db[check] = executor.submit(getattr(Checks, check))
for name, handler in zip(db.keys(), concurrent.futures.as_completed([db[k] for k in db.keys()])):
if handler.exception():
print(f"{str(handler.exception())} was raised by {name}")
else:
print(f"success in {name}")
# all the threads are finished at that point
print("all threads are done")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.