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

本文介绍了三种在Python3中获取协程返回值的方法:通过future的task,使用loop.create_task,以及利用callback。示例代码详细展示了如何在协程完成时触发回调函数,并传递参数。
摘要由CSDN通过智能技术生成

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 g

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值