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

Mar 17, 2024 ยท 2 min read

The asyncio.run() 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")

asyncio.run(main())
asyncio.run(main()) # Probably won't work as expected

When asyncio.run() 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 asyncio.run():

  • 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 asyncio.run() in simple programs and scripts. Use the manual event loop control for advanced use cases.
  • If you do call asyncio.run() multiple times, make sure the event loop from the previous call is fully closed first.
  • So in summary, asyncio.run() 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 "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <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" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: