Python-同时运行多个异步功能
我本质上是在制作一个 pinger,它具有一个包含密钥/Webhook 对的二维列表,在 ping 一个密钥后,将响应发送到一个 webhook,
该二维列表如下所示:
some_list = [["key1", "webhook1"], ["key2", "webhook2"]]
我的程序本质上是一个循环,并且我'我不太确定如何在函数中旋转 some_list
数据。
这是我的脚本的一个小演示:
async def do_ping(some_pair):
async with aiohttp.ClientSession() as s:
tasks = await gen_tasks(s, some_pair)
results = await asyncio.gather(*tasks*)
sleep(10)
await do_ping(some_pair)
我已经尝试过:
async def main():
for entry in some_list:
asyncio.run(do_ping(entry))
但是由于 do_ping
函数是一个自调用循环,它只是一遍又一遍地调用第一个函数,并且永远不会得到给它之后的人。希望找到解决方案,无论是线程还是类似的,如果您有更好的方法来构造 some_list
值(我认为这将是一个字典),请随时放弃该反馈
I'm essentially making a pinger, that makes has a 2d list, of key / webhook pairs, and after pinging a key, send the response to a webhook
the 2d list goes as follows:
some_list = [["key1", "webhook1"], ["key2", "webhook2"]]
My program is essentially a loop, and I'm not too sure how I can rotate the some_list
data, in the function.
Here's a little demo of what my script looks like:
async def do_ping(some_pair):
async with aiohttp.ClientSession() as s:
tasks = await gen_tasks(s, some_pair)
results = await asyncio.gather(*tasks*)
sleep(10)
await do_ping(some_pair)
I've tried:
async def main():
for entry in some_list:
asyncio.run(do_ping(entry))
but due to the do_ping
function being a self-calling loop, it just calls the first one over and over again, and never gets to the ones after it. Hoping to find a solution to this, whether it's threading or alike, and if you have a better way of structuring some_list
values (which I assume would be a dictionary), feel free to drop that feedback as well
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使方法递归
await do_ping(some_pair)
,它永远不会结束main
中的循环继续。我会像这样重构应用程序:或者,您可以将重复和睡眠逻辑移至
main
中:您还可以在调用睡眠之前启动任务,然后收集它们。这将使 ping 更一致地以 10 秒间隔开始,而不是 10 秒 + 收集结果所需的时间:
编辑正如 creolo 您应该只创建一个
ClientSession
对象。请参阅https://docs.aiohttp.org/en/stable/client_reference.htmlYou made your method recursive
await do_ping(some_pair)
, it never ends for the loop inmain
to continue. I would restructure the application like this:Alternatively you could move the repeat and sleeping logic into the
main
:You could also start the tasks before doing a call to sleep, and gather them afterwards. That would make the pings more consistently start at 10 second intervals instead of being 10 seconds + the time it takes to gather the results:
EDIT As pointed out by creolo you should only create a single
ClientSession
object. See https://docs.aiohttp.org/en/stable/client_reference.html