1. 獲取協程返回值,實質就是future中的taskhtml
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, 獲取返回值async
# 獲取協程的返回值 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函數中傳入值oop
# 獲取協程的返回值 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())