Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

python - Retrieve the arguments that were passed to cancelled coroutines/tasks

I am trying to retrieve the arguments that were passed to the coroutines/tasks ran using asyncio.wait after the timeout expires.

For example:

todo = [f(10), f(20), g(20), f(30)]
done, pending = await asyncio.wait(todo, timeout=2.5)

if after 2.5 seconds f(30) hasn't returned and is cancelled, I only see it as <Task pending name='Task-3' coro=<f()... which gives me the matching coroutine f() but no the value of the args ...

Any idea how I could get these args?

Thank you

question from:https://stackoverflow.com/questions/66054468/retrieve-the-arguments-that-were-passed-to-cancelled-coroutines-tasks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Any idea how I could get these args?

A straightforward approach is to attach them to the task before calling wait():

todo = []
for arg in 10, 20, 20, 30:
    task = asyncio.create_task(f(arg))
    task.f_arg = arg
    todo.append(task)
done, pending = await asyncio.wait(todo, timeout=2.5)
# creation arg available in `f_arg` regardless of whether the task
# is done or pending

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...