The run() function of asyncio module in Python

The run() function executes a coroutine on an asynchronous event loop. No event loop should be running while calling the run() function.

Asyncio Updated 19 May 2022 1 min read

Overview

  • The run() method executes a coroutine on an asyncio event loop.

  • Before executing a coroutine, the run() method validates whether the parameter passed is a valid coroutine object. Before executing the coroutine, the method makes sure that no event loop is already running.
  • Unless a custom event loop is used, using the run() method is the recommended way for executing coroutines.

Example

python
# Example Python program that executes

            # coroutine(s) through asyncio.run() function

            import asyncio

# A simple coroutine that simulates collecting

            # orders

            async def get_orders():

                for i in range(1, 11):

                    print("Getting Order:%d"%i)

                    await asyncio.sleep(0)

# A simple coroutine that simulates serving orders

            async def serve_orders():

                for i in range(1, 11):

                    print("Serving Order:%d"%i)

                    await asyncio.sleep(0)

# A coroutine that awaits tasks

            async def main():

                t1 = asyncio.create_task(get_orders())

                t2 = asyncio.create_task(serve_orders())

                await asyncio.wait([t1, t2])

# Execute the main coroutine through asyncio.run()

            evtlp = asyncio.new_event_loop()

            asyncio.set_event_loop(evtlp)

            asyncio.run(main())

Output

Output
Getting Order:1

Serving Order:1

Getting Order:2

Serving Order:2

Getting Order:3

Serving Order:3

Getting Order:4

Serving Order:4

Getting Order:5

Serving Order:5

Getting Order:6

Serving Order:6

Getting Order:7

Serving Order:7

Getting Order:8

Serving Order:8

Getting Order:9

Serving Order:9

Getting Order:10

Serving Order:10