python - Asyncio 不异步执行任务

标签 python asynchronous synchronization python-asyncio

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

#!/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()

这是调用脚本时的输出:

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!

最佳答案

您按顺序调用函数,因此代码也按顺序执行。请记住 await this 的意思是“执行 this等待它返回”(但与此同时,如果 this 选择暂停执行,其他已经在别处开始的任务可能会运行)。

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

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.gather 的文档功能。或者,您也可以使用 asyncio.wait .

关于python - Asyncio 不异步执行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40564057/

相关文章:

python - Pyinstaller - 从最终可执行文件中排除文件

python - QImage 倾斜某些图像,但不倾斜其他图像

asynchronous - React Native 计算繁重的任务

gradle - 错误 Gradle 同步失败 : Failed to find CMake

python - 一种用于跟踪数据库中表历史记录的命令行/API 工具,它是否存在,或者我应该去开发一个吗?

python - 为什么必须扩展和附加 __init__ ?

python - 在 Python 中添加到本地命名空间?

c# - 使用 WCF 异步有好处吗?

c# - TPL 数据流 : design for parallelism while keeping order

python - 在Python2.7中实现Barrier