hourglass

Problem

How do we run an asynchronous function in a synchronous script?

Python’s await async syntax can be a real life-saver when it comes to running highly concurrent code in a performant manner. However, sometimes we just want to call an asynchronous function synchronously.

Maybe we have a small application where performance is not a big issue, or we just want to reuse some async functions in an experimental script. In such situations we do not want to rewrite the whole implementation to use only an asynchronous approach.

Fortunately, with a little bit of understanding, we can do this easily.

Solution

The solution is as simple as structuring the code like this:

Explanation

When we import asyncio we initialise the start of the event loop in python.

With the event loop running in the background, we just need to get it with asyncio.get_event_loop(). We then run the async function, generating a coroutine. Note that this coroutine will not start running immediately.

This is where loop.run_until_complete() comes into play. When any coroutine is passed as an argument to it, as in this case, the coroutine is executed, and the script waits till the coroutine returns. Only after the coroutine returns does the script continue on with the rest of its execution.

Hope this gave you a better idea of how async-await works in Python.