异步 asyncio
一个 event_loop 事件循环
一个 coroutine 协程
async def do_some_work(x):
print("Writing :", x)
return "Done ,2"
把协程放入事件循环中
cor = do_some_work(2)
loop = asyncio.get_event_loop()
loop.run_until_complete(cor)
也可以把协程打包成task – 可以查看协程状态可获取协程返回值
def callback(future):
"""回调函数"""
print("callback", future.result())
cor = do_some_work(2)
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(cor)
task.add_done_callback(callback)
回调需要多个参数
import functools
def callback(x, future):
"""回调函数"""
print("callback", x, future.result())
cor = do_some_work(2)
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(cor)
# 固定函数参数
task.add_done_callback(functools.partial(callback, 2))
不要回调,直接读task的result
task.result()
有阻塞,在协程里使用await, 去执行其他协程
async def do_some_work(x):
print("Writing :", x)
await asynico.sleep(2)
return "Done ,2"