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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With