码迷,mamicode.com
首页 > 编程语言 > 详细

python asyncio 获取协程返回值和使用callback

时间:2020-03-08 19:40:33      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:future   return   就是   cal   结果   await   get   cio   事件   

Reference from: https://www.cnblogs.com/callyblog/p/11216961.html

 

1. 获取协程返回值,实质就是future中的task

技术图片
import asyncio
import time
async def get_html(url):
print("start get url")
await asyncio.sleep(2)
return "bobby"

def callback(url, future):
print(url)
print("send email to bobby")

if __name__ == "__main__":
start_time = time.time()
loop = asyncio.get_event_loop()
get_future = asyncio.ensure_future(get_html("http://www.imooc.com")) # 相当于开启一个future
loop.run_until_complete(get_future) # 事件循环
print(get_future.result()) # 获取结果
技术图片

 

 

2. 使用loop自带的create task, 获取返回值

技术图片
# 获取协程的返回值
import asyncio
import time
from functools import partial
async def get_html(url):
    print("start get url")
    await asyncio.sleep(2)
    return "bobby"

def callback(url, future):
    print(url)
    print("send email to bobby")

if __name__ == "__main__":
    start_time = time.time()
    loop = asyncio.get_event_loop()
    task = loop.create_task(get_html("http://www.imooc.com"))
    loop.run_until_complete(task)
    print(task.result())
技术图片

 

 

3. 使用callback,只要await地方的内容一运行完,就会运行callback

技术图片
# 获取协程的返回值
import asyncio
import time
from functools import partial
async def get_html(url):
    print("start get url")
    await asyncio.sleep(2)
    return "bobby"

def callback(future): #这里默认传入一个future对象
    print("send email to bobby")

if __name__ == "__main__":
    start_time = time.time()
    loop = asyncio.get_event_loop()
    task = loop.create_task(get_html("http://www.imooc.com"))
    task.add_done_callback(callback)
    loop.run_until_complete(task)
    print(task.result())
技术图片

 

 

使用partial这个模块向callback函数中传入值

技术图片
# 获取协程的返回值
import asyncio
import time
from functools import partial
async def get_html(url):
    print("start get url")
    await asyncio.sleep(2)
    return "bobby"

def callback(future):
    print("send email to bobby")

def callback1(url, future): # 传入值的时候,future必须在最后一个
    print(url)
    print("send email to bobby")
if __name__ == "__main__":
    start_time = time.time()
    loop = asyncio.get_event_loop()
    task = loop.create_task(get_html("http://www.imooc.com"))
    task.add_done_callback(partial(callback1, "http://www.imooc.com"))
    loop.run_until_complete(task)
    print(task.result())
技术图片

python asyncio 获取协程返回值和使用callback

标签:future   return   就是   cal   结果   await   get   cio   事件   

原文地址:https://www.cnblogs.com/zhangchenliang/p/12444205.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!