Python3 - Get the result of an asynchronous method
I'm new to Python. I wrote a simple recycling program using asyncio. Here are my code snippets
loop = asyncio.get_event_loop()
task = loop.create_task(conSpi.parse(arguments.url))
value = loop.run_until_complete(asyncio.wait([task]))
loop.close()
I want to print the result returned to a value. Variable print value, it prints something like this
{<Task finished coro=<ConcurrentSpider.parse() done,
defined at /home/afraz/PycharmProjects/the-lab/concurrentspider.py:28> result=3>}
`
How can I only get the result and not print rest?
+3
source to share
1 answer
The easiest way is to write
value = loop.run_until_complete(task)
This only works if you want to wait one task at a time. If you need multiple tasks, you need to use asyncio.wait correctly. It returns a tuple containing completed and pending futures. By default though, pending futures will be empty because it waits for all futures to complete.
So something like
done, pending = loop.run_until_complete(asyncio.wait( tasks))
for future in done:
value = future.result() #may raise an exception if coroutine failed
# do something with value
+5
source to share