运行时错误:无法从正在运行的事件循环中调用 asyncio.run(),这是一个非常简单的程序

问题描述 投票:0回答:1
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
asynchronous python-asyncio aiohttp
1个回答
0
投票
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())
© www.soinside.com 2019 - 2024. All rights reserved.