[英]Asyncio HTTP requests without blocking main thread
我有一個主線程,它總是需要可用於讀取鍵盤按鍵輸入。
在每次按鍵時,我必須運行 4 個功能,例如顯示、保存到文件和發出 HTTP 請求等。
按鍵可以比執行 4 個功能更快。
我的邏輯如下,但看不出如何讓 key_press() 始終運行,因為我必須等待函數在某個時刻完成。
async def main():
async with aiohttp.ClientSession() as client:
while True:
pressed_key = key_press()
if pressed_key != "":
f1 = asyncio.create_task(do_something1())
f2 = asyncio.create_task(do_something2())
f3 = asyncio.create_task(do_something3())
f4 = asyncio.create_task(send_to_API())
await f1,f2,f3,send_to_API
asyncio.run(main())
我是否應該嘗試一些額外的邏輯,在遞歸調用 asyncio.tasks 之后使用更多循環? 或者我應該考慮多線程,讓一個線程處於活動狀態運行 key_press() 並在其他地方進行異步調用? 任何想法或暗示朝着好的方向發展?
如果您嘗試在input
的幫助下模擬 USB 數據 stream(在您的示例中為key_press
function),則必須使用multithreading
模塊,因為input
是阻塞asyncio
並且它將停止線程中的異步循環工作。 要將asyncio
與input
function 結合使用,您必須使用另一個線程,請查看以下示例:
import asyncio
import threading
async def do_work(i):
"""take input key and do some work with the input"""
await asyncio.sleep(5)
print(i)
async def main_thread_loop_work(_key):
"""simulate multiple tasks caused by key input"""
t1 = asyncio.create_task(do_work(_key))
t2 = asyncio.create_task(do_work(_key))
t3 = asyncio.create_task(do_work(_key))
await t1
await t2
await t3
def thead_worker(_key):
"""target function for another thread"""
asyncio.run(main_thread_loop_work(_key))
if __name__ == '__main__':
while True:
some_key = input("Please provide any key: ")
th = threading.Thread(target=thead_worker, args=(some_key, ))
th.start()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.