python-3.x - 我的代码说它无法关闭正在运行的循环
问题描述
我做了一个代码,但它给出了错误,无法关闭正在运行的循环
代码是
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()
请为我修改代码,因为我是新开发人员
如果你能帮助我,我将非常感激
解决方案
这是完整的工作示例:
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)
推荐阅读
- bash - 检查哪个 INI 文件部分具有特定键
- c++ - 在 sfml 中获取可变形的边界框
- python-3.x - 在循环内修改 Tensorflow 变量
- reactjs - 我们可以在内容的单行文本字段中添加下划线吗?
- eclipse - 使用 Eclipse 和 Cygwin 设置 SystemC-AMS - 未定义的参考错误
- reactjs - 在 dotnet core &&react 应用程序中使用 office-ui-fabric
- svg - 如何将数据从 angular 6 typescript 动态传递到 animateTransform“from”属性?
- gitlab - 如何覆盖 GitLab wiki 页面的标题?
- javascript - 在 javascript 中这是什么类型的对象?
- java - 阅读邮件时 Google Gmail API Java 无法按预期工作