Asyncio不会异步执行任务 [英] Asyncio doesn't execute the tasks asynchronously

查看:76
本文介绍了Asyncio不会异步执行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python的 asyncio 模块,但我不知道我的简单代码有什么问题.它不会异步执行任务.

I'm playing around with asyncio module of Python and I don't know what's the problem with my simple code. It doesn't execute the tasks asynchronously.

#!/usr/bin/env python3    

import asyncio
import string    


async def print_num():
    for x in range(0, 10):
        print('Number: {}'.format(x))
        await asyncio.sleep(1)    

    print('print_num is finished!')    

async def print_alp():
    my_list = string.ascii_uppercase    

    for x in my_list:
        print('Letter: {}'.format(x))
        await asyncio.sleep(1)    

    print('print_alp is finished!')    


async def msg(my_msg):
    print(my_msg)
    await asyncio.sleep(1)    


async def main():
    await msg('Hello World!')
    await print_alp()
    await msg('Hello Again!')
    await print_num()    


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()

这是调用脚本时的输出:

Here's the output when the script is called:

Hello World!
Letter: A
Letter: B
Letter: C
Letter: D
Letter: E
Letter: F
Letter: G
Letter: H
Letter: I
Letter: J
Letter: K
Letter: L
Letter: M
Letter: N
Letter: O
Letter: P
Letter: Q
Letter: R
Letter: S
Letter: T
Letter: U
Letter: V
Letter: W
Letter: X
Letter: Y
Letter: Z
print_alp is finished!
Hello Again!
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
print_num is finished!

推荐答案

您正在按顺序调用函数,因此代码也按顺序执行.请记住,等待此的意思是执行 this 然后 wait 使其返回"(但与此同时,如果 this 选择暂停执行,其他已经开始执行的其他任务可能会运行.

You are calling the functions sequentially, so the code also executes sequentially. Remember that await this means "do this and wait for it to return" (but in the meantime, if this chooses to suspend execution, other tasks which have already started elsewhere may run).

如果要异步运行任务,则需要:

If you want to run the tasks asynchronously, you need to:

async def main():
    await msg('Hello World!')
    task1 = asyncio.ensure_future(print_alp())
    task2 = asyncio.ensure_future(print_num())
    await asyncio.gather(task1, task2)
    await msg('Hello Again!')

另请参见 asyncio的文档.收集 函数.另外,您也可以使用 asyncio.wait .

See also the documentation of the asyncio.gather function. Alternatively, you could also use asyncio.wait.

这篇关于Asyncio不会异步执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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