Why do most asyncio examples use loop.run_until_complete ()?

I was looking at Python documentation for asyncio , and I wonder why most examples use loop.run_until_complete() rather than Asyncio.ensure_future() .

For example: https://docs.python.org/dev/library/asyncio-task.html

ensure_future be a much better way to demonstrate the benefits of non-blocking functions. run_until_complete , on the other hand, blocks the loop as synchronous functions.

This makes me feel that I should use run_until_complete instead of a combination of ensure_future with loop.run_forever() to run multiple cooperative routines at the same time.

+5
source share
1 answer

run_until_complete used to run the future until it is complete. It will block the execution of the code following it. However, this triggers an event loop. Any futures that have been scheduled will be executed until the future run_until_complete .

In this example:

 import asyncio async def do_io(): print('io start') await asyncio.sleep(5) print('io end') async def do_other_things(): print('doing other thigns') loop = asyncio.get_event_loop() loop.run_until_complete(do_io()) loop.run_until_complete(do_other_things()) loop.close() 

do_io will be launched. Upon completion, do_other_things will be launched. Your way out will be

 io start io end doing other thigns 

If you plan to do_other_things with an event loop before running do_io , control will switch from do_io to do_other_things when the first is expected.

 loop.create_task(do_other_things()) loop.run_until_complete(do_io()) 

This will give you the result.

This is because do_other_things planned before do_io . There are many different ways to get a conclusion.

 doing other thigns io start io end 

but what meaning makes sense depends on what your application actually does. Therefore, I will leave this as an exercise for the reader.

+5
source

Source: https://habr.com/ru/post/1258501/


All Articles