Asyncio tasks getting cancelled

Léo El Amri leo at superlel.me
Sun Nov 4 17:10:59 EST 2018


On 04/11/2018 20:25, ike at koeln.ccc.de wrote:
> I'm having trouble with asyncio. Apparently tasks (asyncio.create_task)
> are not kept referenced by asyncio itself, causing the task to be
> cancelled when the creating function finishes (and noone is awaiting the
> corresponding futue). Am I doing something wrong or is this expected
> behavior?
> 
> The code sample I tried:
> 
>> import asyncio
>>
>> async def foobar():
>>     print(1)
>>     await asyncio.sleep(1)
>>     print(2)
>>
>> async def main():
>>     asyncio.create_task(foobar())
>>     #await asyncio.sleep(2)
>>
>> loop = asyncio.get_event_loop()
>> asyncio.run(main())
>> loop.run_forever()
> 

I don't know anything about asyncio in Python 3.7, but given the
documentation, asyncio.run() will start a loop and run the coroutine
into it until there is nothing to do anymore, then free the loop it
created. I assume it's kind of a run_forever() with some code before it
to schedule the coroutine.

Thus, I don't think it's appropriate to allocate the loop by yourself
with get_event_loop(), then to run it with run_forever().
Usually, when you're already running into a coroutine, you're using
"await other_coroutine()" instead of
"asyncio.create_task(other_coroutine())".

Buy it should not be the root cause of your issue. With theses
information only, it looks like a Python bug to me (Or an implementation
defined behavior. By the way what is your platform ?).

You could try to change either one of asyncio.create_task() or
asyncio.run() with "older" Python API (Python 3.6, preferably).
In the case of run() it would be a simple loop.create_task(main())
instead of the asyncio.asyncio.run(main()).
In the case of asyncio.create_task() it would be
asyncio.get_event_loop(foobar()).
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).

I don't have Python 3.7 right now, so I can't help further. I hope
someone with knowledge in asyncio under Python 3.7 will be able to help.

- Léo



More information about the Python-list mailing list