RuntimeError: asyncio.run() cannot be called from a running event loop, a very simple program

74 views Asked by At
import asyncio
import aiohttp

async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            data = await response.text()
            return data

async def main():
    urls = [
        'https://example.com',
        'https://google.com',
        'https://openai.com'
    ]

    tasks = [fetch_data(url) for url in urls]
    results = await asyncio.gather(*tasks)
    print(results)

asyncio.run(main())


---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
File c:\Users\Steven\stock.investing.decision.making\my-app\management\real.time.price2.py:21
     18     results = await asyncio.gather(*tasks)
     19     print(results)
---> 21 asyncio.run(main())

File c:\Python312\Lib\asyncio\runners.py:190, in run(main, debug, loop_factory)
    161 """Execute the coroutine and return the result.
    162 
    163 This function runs the passed coroutine, taking care of
   (...)
    186     asyncio.run(main())
    187 """
    188 if events._get_running_loop() is not None:
    189     # fail fast with short traceback
--> 190     raise RuntimeError(
    191         "asyncio.run() cannot be called from a running event loop")
    193 with Runner(debug=debug, loop_factory=loop_factory) as runner:
    194     return runner.run(main)

RuntimeError: asyncio.run() cannot be called from a running event loop
1

There are 1 answers

1
Steven On
import asyncio
import aiohttp

async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            data = await response.text()
            return data

async def main():
    urls = [
        'https://example.com',
        'https://google.com',
        'https://openai.com'
    ]

    tasks = [fetch_data(url) for url in urls]
    results = await asyncio.gather(*tasks)
    print(results)

await(main())