简体   繁体   中英

return a list from asyncio function python

I have this code for scraping printers webpage with asyncio:

def get_toner(url,loop):
    loop.run_in_executor(executor,scraper,url)

def scraper(url):
    
#function for scraping return % of toner

loop = asyncio.get_event_loop()

def main():
    for stampante in lista_totale:
        get_toner(stampante,loop=loop)
        
    lista_verificati.append(loop.run_until_complete(asyncio.gather(*asyncio.all_tasks(loop))))
    print (lista_verificati)

if __name__ == "__main__":
    main()

my intent is to create a list to work with at the end of the loop. But I can't print the complete list, the code only prints the empty list immediately after the function starts.

i have read this:

asyncio-collecting-results-from-an-async-function-in-an-executor

return-results-from-asyncio-get-event-loop

return-a-list-from-asyncio-function

I found the solution with loop.shutdown_asyncgens():

try:
    loop.run_until_complete(asyncio.gather(*asyncio.all_tasks(loop)))
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    executor.shutdown(wait=True)
    loop.close()
    print (lista_verificati)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM