How many times should asyncio run () be called python ?

Mar 17, 2024 ยท 2 min read

The function is used to run the top-level entry point of an asyncio program. It should generally only be called once per program.

Calling it multiple times can lead to unexpected behavior:

import asyncio

async def main():
    print("Hello") # Probably won't work as expected

When is called, it does a few things:

  • Creates an event loop
  • Runs the passed coroutine (e.g. main()) until it finishes
  • Closes the event loop
  • So calling it a second time tries to create and close a new event loop while the existing one may still be open.

    Here are some tips on using

  • Call it only once at the top level of your program. This runs your main() coroutine and manages the event loop for you.
  • If you want to manually control the event loop, use loop = asyncio.new_event_loop() and loop.run_until_complete(main()) instead.
  • Use in simple programs and scripts. Use the manual event loop control for advanced use cases.
  • If you do call multiple times, make sure the event loop from the previous call is fully closed first.
  • So in summary, is designed to be called once. For most programs, calling it only at the top level is sufficient to run the asyncio code. Manually create and manage an event loop if you need more control.

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you

    Try ProxiesAPI for free

    curl ""

    <!doctype html>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />


    Don't leave just yet!

    Enter your email below to claim your free API key: