您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了python如何使用await關鍵字來等另外一個協程,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
一個協程里可以啟動另外一個協程,并等待它完成返回結果,采用await關鍵字,
例子如下:
import asyncio async def outer(): print('in outer') print('waiting for result1') result1 = await phase1() print('waiting for result2') result2 = await phase2(result1) return (result1, result2) async def phase1(): print('in phase1') return 'result1' async def phase2(arg): print('in phase2') return 'result2 derived from {}'.format(arg) event_loop = asyncio.get_event_loop() try: return_value = event_loop.run_until_complete(outer()) print('return value: {!r}'.format(return_value)) finally: event_loop.close() 輸出結果如下: in outer waiting for result1 in phase1 waiting for result2 in phase2 return value: ('result1', 'result2 derived from result1')
await關鍵字添加了一個新的協程到循環里,而不需要明確地添加協程到這個事件循環里。
補充知識:python里使用Condition對象來喚醒指定數量的協程
在asyncio庫里,定義Condition對象,它的行為與事件Event有點像,區別是事件是通知所有對象,Condition對象可以指定一定數量的協程被通知,它是通過函數notify()來實現的,如果參數里放2,就是通知兩個協程,例子如下:
import asyncio async def consumer(condition, n): with await condition: print('consumer {} is waiting'.format(n)) await condition.wait() print('consumer {} triggered'.format(n)) print('ending consumer {}'.format(n)) async def manipulate_condition(condition): print('starting manipulate_condition') # pause to let consumers start await asyncio.sleep(0.1) for i in range(1, 3): with await condition: print('notifying {} consumers'.format(i)) condition.notify(n=i) await asyncio.sleep(0.1) with await condition: print('notifying remaining consumers') condition.notify_all() print('ending manipulate_condition') async def main(loop): # Create a condition condition = asyncio.Condition() # Set up tasks watching the condition consumers = [ consumer(condition, i) for i in range(5) ] # Schedule a task to manipulate the condition variable loop.create_task(manipulate_condition(condition)) # Wait for the consumers to be done await asyncio.wait(consumers) event_loop = asyncio.get_event_loop() try: result = event_loop.run_until_complete(main(event_loop)) finally: event_loop.close()
結果輸出如下:
starting manipulate_condition consumer 2 is waiting consumer 3 is waiting consumer 4 is waiting consumer 1 is waiting consumer 0 is waiting notifying 1 consumers consumer 2 triggered ending consumer 2 notifying 2 consumers consumer 3 triggered ending consumer 3 consumer 4 triggered ending consumer 4 notifying remaining consumers ending manipulate_condition consumer 1 triggered ending consumer 1 consumer 0 triggered ending consumer 0
以上就是關于python如何使用await關鍵字來等另外一個協程的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。