Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...