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())
Python 3.5以上异步IO用法示例
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- CompletableFuture常见用法,CompletableFuture使用示例,CompletableFu...
- asyncio 异步请求(python 3.5 新引用语法) python 3.4 引入了协程的概念。在 pyth...
- 本文是17年写的,至今过去多年,有一篇更好的文档: https://superfastpython.com/pyt...
- EasyUI用法: 把EasyUI下载到本地,然后看文档找到自己想要的样式,然后写到自己的代码里(推荐看源码里的d...