您好,登錄后才能下訂單哦!
小編這次要給大家分享的是在python里如何創(chuàng)建一個(gè)任務(wù),文章內(nèi)容豐富,感興趣的小伙伴可以來(lái)了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
與事件循環(huán)進(jìn)行交互,最基本的方式就是任務(wù),任務(wù)封裝了協(xié)程和自動(dòng)跟蹤它的狀態(tài)。任務(wù)是Future類的子類,所以其它協(xié)程可以等待任務(wù)完成,或當(dāng)這些任務(wù)完成獲取返回結(jié)果。
在這里通過(guò)create_task()函數(shù)來(lái)創(chuàng)建一個(gè)任務(wù)實(shí)例,然后事件循環(huán)就運(yùn)行這個(gè)任務(wù),直到這個(gè)任務(wù)返回為止:
import asyncio async def task_func(): print('in task_func') return 'the result' async def main(loop): print('creating task') task = loop.create_task(task_func()) print('waiting for {!r}'.format(task)) return_value = await task print('task completed {!r}'.format(task)) print('return value: {!r}'.format(return_value)) event_loop = asyncio.get_event_loop() try: event_loop.run_until_complete(main(event_loop)) finally: event_loop.close()
結(jié)果輸出如下:
creating task
waiting for <Task pending coro=<task_func() running at D:\work\csdn\python_Game1\example\asyncio_create_task.py:4>>
in task_func
task completed <Task finished coro=<task_func() done, defined at D:\work\csdn\python_Game1\example\asyncio_create_task.py:4> result='the result'>
return value: 'the result'
補(bǔ)充知識(shí):python里創(chuàng)建任務(wù)執(zhí)行一半時(shí)取消任務(wù)執(zhí)行
下例子來(lái)演示創(chuàng)建任務(wù)執(zhí)行一半時(shí)取消任務(wù)執(zhí)行,這時(shí)會(huì)拋出異常CancelledError,同時(shí)也提供了一個(gè)機(jī)會(huì)來(lái)刪除占用資源等等:
import asyncio async def task_func(): print('in task_func, sleeping') try: await asyncio.sleep(1) except asyncio.CancelledError: print('task_func was canceled') raise return 'the result' def task_canceller(t): print('in task_canceller') t.cancel() print('canceled the task') async def main(loop): print('creating task') task = loop.create_task(task_func()) loop.call_soon(task_canceller, task) try: await task except asyncio.CancelledError: print('main() also sees task as canceled') event_loop = asyncio.get_event_loop() try: event_loop.run_until_complete(main(event_loop)) finally: event_loop.close()
結(jié)果輸出如下:
creating task
in task_func, sleeping
in task_canceller
canceled the task
task_func was canceled
main() also sees task as canceled
看完這篇關(guān)于在python里如何創(chuàng)建一個(gè)任務(wù)的文章,如果覺(jué)得文章內(nèi)容寫(xiě)得不錯(cuò)的話,可以把它分享出去給更多人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。