Asyncio tasks getting cancelled
Léo El Amri
leo at superlel.me
Mon Nov 5 04:55:56 EST 2018
On 05/11/2018 07:55, Ian Kelly wrote:
>> I assume it's kind of a run_forever() with some code before it
>> to schedule the coroutine.
>
> My understanding of asyncio.run() from
> https://github.com/python/asyncio/pull/465 is that asyncio.run() is
> more or less the equivalent of loop.run_until_complete() with
> finalization, not loop.run_forever(). Thus this result makes sense to
> me: asyncio.run() runs until main() finishes, then stops. Without the
> sleep(2), main() starts creates the foobar() task and then returns
> without awaiting it, so the sleep(1) never finishes. asyncio.run()
> also finalizes its event loop, so I assume that the loop being
> run_forever must be a different event loop since running it doesn't
> just raise an exception. Therefore it doesn't resume the foobar()
> coroutine since it doesn't know about it.
That totally make sense. I agree with this supposition.
> If the goal here is for the task created by main() to complete before
> the loop exits, then main() should await it, and not just create it
> without awaiting it.
I said the following:
> Usually, when you're already running into a coroutine, you're using
> "await other_coroutine()" instead of
> "asyncio.create_task(other_coroutine())".
Which is not accurate. What Ian said is accurate. One indeed may need to
schedule a coroutine in some situation. I just assumed that's wasn't
what the OP intended to do given the name of the "main" function.
I also said:
> But anyway, I highly recommend you to use the "await other_coroutine()"
> syntax I talked about earlier. It may even fix the issue (90% chance).
This should indeed fix the issue, but this is definitely not what one is
looking for if one really want to _schedule_ a coroutine.
- Léo
More information about the Python-list
mailing list