Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting "RuntimeError: yield was used instead of yield from for generator in task Task" while trying to use asyncio?

import asyncio

f = open('filename.txt', 'w')

@asyncio.coroutine
def fun(i):
    print(i)
    f.write(i)
    # f.flush()

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.as_completed([fun(i) for i in range(3)]))
    f.close()

main()

I'm trying to use python3's new library asyncio .but I'm getting this error dont know why. any help would be appreciated.

like image 499
micheal Avatar asked Feb 06 '15 18:02

micheal


Video Answer


1 Answers

The specific error you're hitting is because you're trying to pass the return value of asyncio.as_completed to run_until_complete. run_until_complete expects a Future or Task, but as_completed returns an iterator. Replace it with asyncio.wait, which returns a Future, and the program will run fine.

Edit:

Just for reference, here's an alternative implementation that uses as_completed:

import asyncio

@asyncio.coroutine
def fun(i):
    # async stuff here
    print(i)
    return i

@asyncio.coroutine
def run():
    with open('filename.txt', 'w') as f:
        for fut in asyncio.as_completed([fun(i) for i in range(3)]):
           i = yield from fut
           f.write(str(i))

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())


main()
like image 67
dano Avatar answered Oct 06 '22 00:10

dano