【问题标题】:My code says that it is unable to close a running loop我的代码说它无法关闭正在运行的循环
【发布时间】:2020-12-01 07:23:39
【问题描述】:

我编写了一个代码,但它给出了无法关闭正在运行的循环的错误

代码是

import aiohttp
import asyncio


async def get_response(query):
    async with aiohttp.ClientSession() as ses:
        async with ses.get(
            f'https://some-random-api.ml/chatbot?message={query}'
        ) as resp:
            return (await resp.json()),['response']
    
#using an event loop
loop = asyncio.get_event_loop()
Task = asyncio.gather(*[get_response('world') for _ in range(500)])

try:
    loop.run_until_complete(Task)
finally:
    loop.close()

请为我修改代码,因为我是新开发者

如果你能帮助我,我将不胜感激

【问题讨论】:

标签: python-3.x python-asyncio aiohttp


【解决方案1】:

这里是完整的工作示例:

import aiohttp
import asyncio


_sem = None


async def get_response(query):
    async with _sem:
        async with aiohttp.ClientSession() as ses:
            async with ses.get(f'http://httpbin.org/get?test={query}') as resp:
                return (await resp.json())['args']


async def main():
    global _sem
    _sem = asyncio.Semaphore(10)  # read https://stackoverflow.com/q/48483348/1113207

    return await asyncio.gather(*[get_response(i) for i in range(20)])

   
res = asyncio.run(main())
print(res)

【讨论】:

  • 嘿,mikhail,我们不能用现有循环调用循环
  • @Reejit 您可能正在使用 Jupyter Notebook 运行代码?如果是这种情况,只需将res = asyncio.run(main()) 替换为res = await main()Jupyter handles the event loop automatically.
  • 嘿,mikhail,它说等待在外面
  • @Reejit 好的,如果你将res = asyncio.run(main()) 替换为res = asyncio.get_event_loop().run_until_complete(main()) 会怎样?
  • 你能帮帮我吗
【解决方案2】:

我建议使用asyncio.run()函数来运行顶级入口点main()函数:

import aiohttp
import asyncio


async def get_response(query):
    async with aiohttp.ClientSession() as ses:
        async with ses.get(
                f'https://httpbin.org/json'
        ) as resp:
            return (await resp.json()), ['response']


async def main():
    res = await asyncio.gather(*[get_response('world') for _ in range(500)])

asyncio.run(main())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2022-10-30
    相关资源
    最近更新 更多