先理解协程(协程有多种写法,效果都是一样得),来自廖雪峰和评论
输出为:
对于开头得理解解释:
下面一些截图来自B站得协程教学视频
Python3.7+协程一般的写法
Python3.7官方文档
用async定义,await + 可等待对象用(协程对象,Future,Task对象),asyncio.run()运行协程
单个任务
import asyncio
async def a():
print('aaaa')
await asyncio.sleep(1)
print('end')
return 'return'
print(asyncio.run(a()))
多个任务(使用task)
等价成下面这个
Python3.7之前协程的写法
import asyncio
async def hello_world():
print("Hello World!")
loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(hello_world())
loop.close()
官方例子:
python3.6文档
过程图解
Task对象文档解释
Future对象
async def set_after(fut, delay, value):
# Sleep for *delay* seconds.
await asyncio.sleep(delay)
# Set *value* as a result of *fut* Future.
fut.set_result(value)
async def main():
# Get the current event loop.
loop = asyncio.get_running_loop()
# Create a new Future object.
fut = loop.create_future()
# Run "set_after()" coroutine in a parallel Task.
# We are using the low-level "loop.create_task()" API here because
# we already have a reference to the event loop at hand.
# Otherwise we could have just used "asyncio.create_task()".
loop.create_task(
set_after(fut, 1, '... world'))
print('hello ...')
# Wait until *fut* has a result (1 second) and print it.
print(await fut)
asyncio.run(main())