Skip to main content
 首页 » 编程设计

python之在 Python 中使用异步

2025年05月04日13小虾米

刚开始用Python学习asyncio,写了如下代码:

import asyncio 
loop = asyncio.get_event_loop() 
 
 
async def hello(): 
    print("Hello") 
    await asyncio.sleep(3) 
    print("World") 
 
if __name__ == '__main__': 
    for i in range(3): 
        loop.run_until_complete(hello()) 
    loop.close() 

这给了我以下输出:

Hello 
<waits for 3 seconds> 
World 
Hello 
<waits for 3 seconds> 
World 
Hello 
<waits for 3 seconds> 
World 

我如何修改程序以便异步处理相同的程序(即一旦第一个任务休眠,第二个任务开始执行),基本上给出类似这样的输出:

Hello 
Hello 
Hello 
World 
World 
World 

请您参考如下方法:

您可以asyncio.gather 它们。

import asyncio 
 
 
async def hello(): 
    print("Hello") 
    await asyncio.sleep(3) 
    print("World") 
 
async def lots_of_hello(): 
    cur_list = [] 
    for _ in range(3): 
        cur_list.append(hello()) 
    await asyncio.gather(*cur_list) 
 
if __name__ == '__main__': 
    loop = asyncio.get_event_loop() 
    loop.run_until_complete(lots_of_hello()) 
    loop.close()