problem using asyncio

87 views
Skip to first unread message

AJAY AJITH

unread,
May 4, 2018, 7:44:56 AM5/4/18
to python-tulip
hi, Im a beginner in asyncio. I was trying out some small scripts to bet the basic idea of asyncio. The below script is meant to print "hello" after some time period "after" is expired. But i have a strange output when i dont use asyncio.wait() inside run_until_complete().


code 1 :

    async def say_hello(after):
    await asyncio.sleep(after)
    print('hello  {0}'.format(after),end='--\n')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    a = count()
    coros = []
    tasks = []
    for i in range(10):
        #coros.append(say_hello(i))
        tasks.append(asyncio.ensure_
future(say_hello(i)))
    tasks = asyncio.wait(tasks)
    loop.run_until_complete(tasks)

output

hello  0--
hello  1--
hello  2--
hello  3--
hello  4--
hello  5--
hello  6--
hello  7--
hello  8--
hello  9--

this works as intended.

code 2:
    async def say_hello(after):
    await asyncio.sleep(after)
    print('hello  {0}'.format(after),end='--\n')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    a = count()
    coros = []
    tasks = []
    for i in range(10):
        #coros.append(say_hello(i))
        tasks.append(asyncio.ensure_future(say_hello(i)))
    #tasks = asyncio.wait(tasks)
    loop.run_until_complete(tasks[6])

output
hello  0--
hello  1--
hello  2--
hello  3--
hello  4--
hello  5--
hello  6--

why did it give such an output?

Idan Haim Shalom

unread,
Dec 3, 2018, 9:42:45 AM12/3/18
to python-tulip
Hi,
In code 2 you only wait for tasks[6] to be complete and then your program finish
that is why the program prints until hello 6-- and exit change it to the last task 9 and you will see all the output.
you can use the loop.run_forever() but then your program will never quit until you will close the loop.
That why you need the asyncio.wait(tasks) 
Reply all
Reply to author
Forward
0 new messages