在python里創(chuàng)建一個(gè)任務(wù)(Task)實(shí)例
與事件循環(huán)進(jìn)行交互,最基本的方式就是任務(wù),任務(wù)封裝了協(xié)程和自動(dòng)跟蹤它的狀態(tài)。任務(wù)是Future類的子類,所以其它協(xié)程可以等待任務(wù)完成,或當(dāng)這些任務(wù)完成獲取返回結(jié)果。
在這里通過create_task()函數(shù)來創(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í)行
下例子來演示創(chuàng)建任務(wù)執(zhí)行一半時(shí)取消任務(wù)執(zhí)行,這時(shí)會(huì)拋出異常CancelledError,同時(shí)也提供了一個(gè)機(jī)會(huì)來刪除占用資源等等:
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
以上這篇在python里創(chuàng)建一個(gè)任務(wù)(Task)實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python讀取指定字節(jié)長(zhǎng)度的文本方法
今天小編就為大家分享一篇python讀取指定字節(jié)長(zhǎng)度的文本方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-08-08
詳解python selenium 爬取網(wǎng)易云音樂歌單名
這篇文章主要介紹了python selenium爬取網(wǎng)易云音樂歌單名,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03

