[英]how to parse response immediately with asyncio.gather?
async def main():
uuids = await get_uuids_from_text_file()
tasks = []
# create a task for each uuid
# and add it to the list of tasks
for uuid in uuids:
task = asyncio.create_task(make_hypixel_request(uuid))
tasks.append(task)
# wait for all the tasks to finish
responses = await asyncio.gather(*tasks)
# run the functions to process the data
for response in responses:
print(response['success'])
data2 = await anti_sniper_request(response)
await store_data_in_json_file(response, data2)
await compare_stats(response)
# loop the main function
async def main_loop():
for _ in itertools.repeat([]):
await main()
# run the loop
loop = asyncio.get_event_loop()
loop.run_until_complete(main_loop())
loop.close()
基本上這是我的代碼函數有非常清晰和解釋性的名稱 make_hypixel_requests 部分我在那里沒有問題,請求立即並行執行,問題是在那之后當“響應中的響應”變得很慢時? 我如何立即獲得響應並快速循環? 我會嘗試附加一個 gif。
原因是因為在等待所有響應返回之后,你在循環中而不是異步地處理它們,因為沒有一個請求似乎相互依賴,等待它們全部完成再處理它們沒有意義,處理這個問題的最好方法是將請求和處理結合起來,例如
async def request_and_process(uuid):
response = await make_hypixel_request(uuid)
print(response['success'])
compare_stats_task = asyncio.create_task(compare_stats(response))
data2 = await anti_sniper_request(response)
await asyncio.gather(store_data_in_json_file(response, data2), compare_stats_task)
async def main():
while True:
uuids = await get_uuids_from_text_file()
await asyncio.gather(*map(request_and_process, uuids))
asyncio.run(main())
您可以使用asyncio.wait
並在至少完成一項任務時返回,然后繼續等待掛起的任務。 asyncio.wait
返回一個包含兩組的元組,第一個包含已完成的任務,第二個包含仍未完成的任務。 您可以調用已完成任務的result
方法並獲取其返回值。
async def main():
uuids = await get_uuids_from_text_file()
tasks = []
# create a task for each uuid
# and add it to the list of tasks
for uuid in uuids:
task = asyncio.create_task(make_hypixel_request(uuid))
tasks.append(task)
# wait for all the tasks to finish
while tasks:
done_tasks, tasks = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for done in done_tasks:
response = done.result()
print(response['success'])
data2 = await anti_sniper_request(response)
await store_data_in_json_file(response, data2)
await compare_stats(response)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.