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

Python asyncio.loop.run_until_complete() function (with examples)

Last updated: August 04, 2023

This pithy, straight-to-the-point article is about the asyncio.loop.run_until_complete() method in modern Python programming (with async/await).

Overview

The asyncio.loop.run_until_complete() method was added to Python in version 3.4, as part of the asyncio module that provides support for concurrency.

The method is used to run a future (an instance of asyncio.Future) or a coroutine object until it is completed, and returns its result or raises its exception. A future is an object that represents the outcome of an asynchronous operation. A coroutine is a function that can be paused and resumed and can await on other coroutines or futures.

Syntax:

loop.run_until_complete(future)

Where:

  • loop is an instance of asyncio.AbstractEventLoop
  • future is a future or a coroutine object that needs to be executed until completion. If the parameter is a coroutine object, it is implicitly scheduled to run as an asyncio.Task. A task is a subclass of future that wraps a coroutine and executes it in an event loop.

The asyncio.loop.run_until_complete() method is useful when you need to run a single future or coroutine object until it is finished and obtain its result or exception. It will block the execution of the code following it until the future or coroutine object is done.

Enough of boring text. Let’s write some to make our hands dirty.

Examples

Using run_until_complete() with a coroutine

Let’s see the basic usage of loop.run_until_complete() with a coroutine object in this example. I’ll provide the code first and then explain it later:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio


async def welcome():
    print("Welcome to Sling Academy!")
    await asyncio.sleep(2)
    print("I hope you have a great day!")


loop = asyncio.get_event_loop()
loop.run_until_complete(welcome())
loop.close()

This example creates a simple coroutine function named welcome() that prints “Welcome to Sling Academy!”, waits for two seconds, and then prints “I hope you have a great day!”. It then gets the current event loop, runs the welcome() coroutine until it is completed using run_until_complete(), and finally closes the loop.

Using run_until_complete() with a future

In this example, we’ll use run_until_complete() with a future object. As before, take a look at the code first:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio

def callback(future):
    print(f"Callback: {future.result()}")

async def main():
    print("Creating future")
    future = loop.create_future()
    print("Adding callback to future")
    future.add_done_callback(callback)
    print("Setting result of future")
    await asyncio.sleep(3)
    future.set_result("Done")


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

The code snippet above creates a custom future object using loop.create_future(), and adds a callback function to it that prints its result. It then creates a main() coroutine that sets the result of the future after three seconds. It then runs the main() coroutine until it is completed using run_until_complete(), and, last but not least, closes the loop.

Output:

Creating future
Adding callback to future
Setting result of future
Callback: Done

The first three prints show up first. The last one comes after a delay.

Next Article: Python: How to Define and Call Asynchronous Functions

Previous Article: Python asyncio.sleep() function (with examples)

Series: Python Asynchronous Programming Tutorials

Python

You May Also Like

  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots
  • Monitoring Order Book Imbalances for Trading Signals via cryptofeed
  • Detecting Arbitrage Opportunities Across Exchanges with cryptofeed