Python 3.5以上异步IO用法示例

import asyncio
import time


async def say_hello_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

# 正常执行,异步操作,总耗时4秒。
async def say_hello_await_without_parenthesis_task():
    print(f"starts at {time.strftime('%X')}")
    task1 = asyncio.create_task(say_hello_after(4, "without_parenthesis_1"))
    task2 = asyncio.create_task(say_hello_after(2, "without_parenthesis_2"))
    await task1
    await task2
    print(f"ends at {time.strftime('%X')}")


# 无法运行,会提示task1和task2不是callable。
# 原因:asyncio.create_task返回的是asyncio.Task类型,而该类型本来就不是callable的,所以会报错。
async def say_hello_await_with_parenthesis_task():
    print(f"starts at {time.strftime('%X')}")
    task1 = asyncio.create_task(say_hello_after(2, "with_parenthesis_1"))
    task2 = asyncio.create_task(say_hello_after(4, "with_parenthesis_2"))
    await task1()
    await task2()
    print(f"ends at {time.strftime('%X')}")

# 正常执行,两次say_hello_after会串行执行,总耗时6秒。
# 原因:当await直接用在协程上的时候,会等待其执行完再执行下一条指令,相当于串行执行。
async def say_hello_with_coro():
    print(f"starts at {time.strftime('%X')}")
    await say_hello_after(4, "without_parenthesis_1")
    await say_hello_after(2, "without_parenthesis_2")
    print(f"ends at {time.strftime('%X')}")


# 无法运行,会提示coroutine没有被awaited。
def say_hello_with_direct_call():
    print(f"starts at {time.strftime('%X')}")
    say_hello_after(4, "without_parenthesis_1")
    say_hello_after(2, "without_parenthesis_2")
    print(f"ends at {time.strftime('%X')}")


if __name__ == '__main__':
    asyncio.run(say_hello_await_without_parenthesis_task())

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容