如何从 python 中的未来检索任务?
How to retrieve a task from a future in python?
假设我有以下代码运行 并行执行多个任务。
with concurrent.futures.ThreadPoolExecutor(max_workers=connections) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
executor,
fun,
arg
)
for i in range(connections)
]
for result in await asyncio.gather(*futures):
# I want to access the futures task here
pass
是否可以在执行后读取期货的任务?
Is it possible to read the the futures' task once it has been executed?
在asyncio中,task这个词有专门的含义,指的是class that subclasses Future
专门用来驱动协程的
在您的代码中,asyncio.gather()
returns 结果,您还有包含 Future
对象的 futures
变量,这些对象也可用于访问相同的对象结果。如果您需要访问其他信息(如原始 fun
或 arg
),您可以将其附加到适当的 Future
或使用 dict 来映射它。例如:
futures = []
for conn in connections:
fut = loop.run_in_executor(executor, fun, arg)
fut.conn = conn # or other info you need
await asyncio.wait(futures)
# at this point all the futures are done, and you can use future.result()
# to access the result of an individual future, and future.conn to obtain
# the connection the future was created for
假设我有以下代码运行 并行执行多个任务。
with concurrent.futures.ThreadPoolExecutor(max_workers=connections) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
executor,
fun,
arg
)
for i in range(connections)
]
for result in await asyncio.gather(*futures):
# I want to access the futures task here
pass
是否可以在执行后读取期货的任务?
Is it possible to read the the futures' task once it has been executed?
在asyncio中,task这个词有专门的含义,指的是class that subclasses Future
专门用来驱动协程的
在您的代码中,asyncio.gather()
returns 结果,您还有包含 Future
对象的 futures
变量,这些对象也可用于访问相同的对象结果。如果您需要访问其他信息(如原始 fun
或 arg
),您可以将其附加到适当的 Future
或使用 dict 来映射它。例如:
futures = []
for conn in connections:
fut = loop.run_in_executor(executor, fun, arg)
fut.conn = conn # or other info you need
await asyncio.wait(futures)
# at this point all the futures are done, and you can use future.result()
# to access the result of an individual future, and future.conn to obtain
# the connection the future was created for