Non-blocking execution with asynchronous Python functions

Asked

Viewed 153 times

1

I want a certain flow to continue even calling a async.sleep() in the code, I have the following code

import asyncio

async def funcao_1(name):
    print("entrando no sono...")
    await asyncio.sleep(3)
    print("saindo do sono...")

async def main():
    result = await asyncio.gather(funcao_1())


loop = asyncio.get_event_loop()

loop.run_until_complete(main())
print("rodando depois do run_until_complete")

Expected exit

entrando no sono...
rodando depois do run_until_complete
saindo do sono...

Return exit

entrando no sono...
saindo do sono...
rodando depois do run_until_complete

Python version

$ python3 --version
Python 3.6.7rc1

Is there any way to do this in Python?

1 answer

3


To run two tasks concurrently, use the function async.gather.

Example:

import asyncio

async def funcao1():
    print('entrando no sono...')
    await asyncio.sleep(3)
    print('saindo do sono...')

async def funcao2():
    print('rodando de forma independente!')

async def main():
    await asyncio.gather(funcao1(), funcao2())

if __name__ == '__main__':
    # Se a versão do seu Python for menor que 3.7, use o seguinte:
    #
    # loop = asyncio.get_event_loop()
    # loop.run_until_complete(main())

    asyncio.run(main())

Terminal output:

entrando no sono...
rodando de forma independente!
saindo do sono...

Documentation: https://docs.python.org/3/library/asyncio-task.html#running-tasks-concurrently

  • there is another way without using the function gather? type in my initial proposal to run an execution after the run_until_complete(main()) or asyncio.run(main())

  • @Daviwesley Codes that will be executed concurrently should be marked as async, so I created two separate functions and marked them with async. If the code is not marked as async, The Event loop has no way of controlling the execution and therefore has no way of being a competitor. If you don’t want to use Event loop for some reason, you’ll have to use threads directly, but I recommend using only async, because the end result gets more expressive and simple than using threads directly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.