asyncio - how to stop background task cleanly

Marko Rauhamaa marko at pacujo.net
Sat Feb 6 03:39:37 EST 2016


"Frank Millman" <frank at chagford.com>:

> When shutting the main program down, I want to stop the task, but I
> cannot figure out how to stop it cleanly - i.e. wait until it has
> finished the current task and possibly performed some cleanup, before
> continuing.

Here (and really, only here) is where asyncio shows its superiority over
threads: you can multiplex.

You should

   await asyncio.wait(..., return_when=asyncio.FIRST_COMPLETED)

to deal with multiple alternative stimuli.

In fact, since there is always a minimum of two alternative stimuli to
await, you should only ever await asyncio.wait().

And, while viable, that's what makes every asyncio program ugly as hell.


Marko



More information about the Python-list mailing list