Sling Academy
Home/Python/Python asyncio.run() function (with examples)

Python asyncio.run() function (with examples)

Last updated: July 10, 2023

Overview

The asyncio.run() function was introduced in Python 3.7 (which was released in 2018). It is a high-level API that creates an event loop, runs the coroutine in the event loop, and finally closes the event loop when the coroutine is complete. It returns the final result of the coroutine or raises an exception if the coroutine fails.

Syntax:

asyncio.run(coro, *, debug=False)

Where:

  • coro is a coroutine object that you want to run in an event loop. A coroutine is a special kind of function that can pause and resume its execution using the async and await keywords.
  • debug is an optional keyword argument that controls the debug mode of the event loop. If True, the event loop will log more information, check for common errors, and enable the asyncio.debugger module. The default value is False.

It is recommended to use the asyncio.run() function as the main entry point for asyncio programs unless you need more fine-grained control over the event loop.

Examples

Running a Simple Coroutine

A simple program that prints two parts of a sentence with a delay between:

import asyncio

async def main():
    print('Welcome to ...')
    await asyncio.sleep(3)
    print('... Sling Academy!')

asyncio.run(main())

Asynchronous I/O

This example demonstrates using asyncio.run() to handle asynchronous I/O operations. It is useful for performing I/O-bound operations concurrently, improving efficiency by not blocking the event loop while waiting for I/O operations to complete.

import asyncio

async def download_file(url):
    # Simulate file download
    await asyncio.sleep(3)
    print(f"Successfully downloaded file from {url}")

async def main():
    tasks = [
        asyncio.create_task(download_file("https://api.slingacademy.com/v1/sample-data/files/customers.csv")),

        asyncio.create_task(download_file("https://api.slingacademy.com/v1/sample-data/files/employees.json")),
    ]
    await asyncio.gather(*tasks)

asyncio.run(main())

In the code above, the download_file() coroutine uses asyncio.sleep() to simulate file downloads. In the main() coroutine, we create tasks for each file download and await their completion using asyncio.gather().

Next Article: Python asyncio.wait_for() function (with examples)

Previous Article: Python asyncio: What are coroutines and event loops?

Series: Python Asynchronous Programming Tutorials

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types