在Python中进行异步循环 [英] Making async for loops in Python

查看:167
本文介绍了在Python中进行异步循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码输出如下:

1 sec delay, print "1", 
1 sec delay, print "2", 
1 sec delay, print "1", 
1 sec delay, print "2"

如何修改使其像这样运行:

How can it be modified to run like this:

1 sec delay, print "1", print "1",
1 sec delay, print "2", print "2"

我希望它运行,以便for循环的两个实例开始同时执行.在执行每个实例时,它们将同时遇到first()函数,然后同时遇到second()函数,因此按上述顺序打印.

I would like it to run so that both instances of the for loop begin executing at the same time. As each instance executes, they will encounter the first() function at the same time, then the second() function at the same time, thus printing in the order mentioned above.

代码:

import asyncio

async def first():
    await asyncio.sleep(1)
    return "1"

async def second():
    await asyncio.sleep(1)
    return "2"

async def main():     
    for i in range(2):
      result = await first()
      print(result)
      result2 = await second()
      print(result2)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

推荐答案

查看所需的输出,似乎目标是保持单个迭代不变,即先运行 first second -并行执行两个循环迭代.

Looking at the desired output, it seems that the goal is to leave the individual iteration as it is - i.e. run first and second sequentially - but execute both loop iterations in parallel.

假设您只想修改 main(),可以这样实现:

Assuming you only want to modify main(), it could be achieved like this:

async def main():
    async def one_iteration():
        result = await first()
        print(result)
        result2 = await second()
        print(result2)
    coros = [one_iteration() for _ in range(2)]
    await asyncio.gather(*coros)

上面的代码不是按顺序进行迭代,而是为每个迭代任务创建一个协程,并使用 asyncio.gather 并行执行所有迭代.

Instead of iterating in sequence, the above creates a coroutine for each iteration task, and uses asyncio.gather to execute all the iterations in parallel.

请注意,仅创建协程不会开始执行它,因此大量的 coros 不会阻塞事件循环.

Note that simply creating a coroutine doesn't start executing it, so a large number of coros won't block the event loop.

这篇关于在Python中进行异步循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆