python中利用Future對象異步返回結(jié)果示例代碼
前言
本文主要給大家介紹了關(guān)于python中用Future對象異步返回結(jié)果的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧。
一個Future是用來表示將來要完成的結(jié)果,異步循環(huán)可以自動完成對這種對象的狀態(tài)觸發(fā)。
例子如下:
import asyncio def mark_done(future, result): print('setting future result to {!r}'.format(result)) future.set_result(result) event_loop = asyncio.get_event_loop() try: all_done = asyncio.Future() print('scheduling mark_done') event_loop.call_soon(mark_done, all_done, 'the result') print('entering event loop') result = event_loop.run_until_complete(all_done) print('returned result: {!r}'.format(result)) finally: print('closing event loop') event_loop.close() print('future result: {!r}'.format(all_done.result()))
輸出結(jié)果如下:
scheduling mark_done entering event loop setting future result to 'the result' returned result: 'the result' closing event loop future result: 'the result'
在這個例子里,并沒有調(diào)用return語句,但也可以生成一個結(jié)果返回。Future的使用跟協(xié)程使用是一樣的。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章

sklearn線性邏輯回歸和非線性邏輯回歸的實(shí)現(xiàn)

python獲取android設(shè)備的GPS信息腳本分享

Pandas時間類型轉(zhuǎn)換與處理的實(shí)現(xiàn)示例

python的命名規(guī)則知識點(diǎn)總結(jié)

python中內(nèi)置庫os與sys模塊的詳細(xì)介紹

pytest實(shí)戰(zhàn)技巧之參數(shù)化基本用法和多種方式

關(guān)于Python中flask-httpauth庫用法詳解

Python re.sub 反向引用的實(shí)現(xiàn)