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。
基本上這是問題:

uj5u.com熱心網友回復:
原因是因為在等待所有回應回傳之后,你在回圈中處理它們而不是異步處理它們,因為沒有一個請求似乎相互依賴,在處理它們之前等待它們全部完成是沒有意義的,處理這個問題的最好方法是將請求和處理結合起來,例如
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())
uj5u.com熱心網友回復:
您可以asyncio.wait在至少完成一項任務時使用并回傳,然后繼續等待待處理的任務。asyncio.wait回傳一個包含兩個集合的元組,第一個包含已完成的任務,第二個包含尚未完成的任務。您可以呼叫resultdone 任務的方法并獲取其回傳值。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471677.html
標籤:Python python-3.x 多线程 异步 蟒蛇异步
上一篇:如何從每個渲染的元素呼叫api
