[英]Run two async functions without blocking each other
我有一個異步功能,我想“並行”運行另一個。 但是我需要在第一個函數中的某個特定時間執行此操作。
我已經看到了很多示例,但是所有這些示例都同時啟動了兩個功能,而這並不是我想要的。
我創建了這個簡單的示例來說明我想要實現的目標(以及我嘗試過的目標):
import asyncio
import time
async def print_letters():
for letter in ['A', 'B', 'C', 'D']:
print(letter)
time.sleep(1)
async def print_numbers(loop):
for number in range(1, 7):
if(number == 3):
# same result with create_task
# loop.create_task(print_letters())
asyncio.ensure_future(print_letters())
print(number)
time.sleep(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(print_numbers(loop))
print('End')
當前輸出:
1,2,3,4,5,6,A,B,C,D,結束
所需的輸出將是這樣的:
1,2,3,A,4,B,5,C,6 D,末端
我嘗試了其他一些東西(例如asyncio.wait
),但沒有一個按預期工作。 另外,當您asyncio
Python asyncio
時,很難理解asyncio
。
如果問題不清楚或缺少某些內容,請告訴我,以便我進行編輯。 我感謝任何幫助。
的Python 3.6.2
您需要異步函數來在等待時釋放CPU,以便其他異步函數有運行的機會。 使用await
關鍵字完成CPU的生成。 另外,您需要使用asyncio
定義的sleep(...)
函數作為正常時間asyncio
time.sleep(...)
不允許重新輸入產生的函數。 總而言之,這要求您的程序必須
import asyncio
async def print_letters():
for letter in ['A', 'B', 'C', 'D']:
print(letter)
await asyncio.sleep(1)
async def print_numbers(loop):
for number in range(1, 7):
if(number == 3):
# same result with create_task
# loop.create_task(print_letters())
asyncio.ensure_future(print_letters())
print(number)
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(print_numbers(loop))
print('End')
因此,你實際上需要做的,是取代time.sleep(...)
用await asyncio.sleep(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.