mic*_*al 4 python python-3.x python-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()
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用python3的新库。asyncio但是我收到此错误,不知道为什么。任何帮助,将不胜感激。
您遇到的特定错误是因为您试图将返回值传递asyncio.as_completed给run_until_complete。run_until_complete需要一个Future或Task,但as_completed返回一个迭代器。将其替换为asyncio.wait,将返回Future,程序将正常运行。
编辑:
仅供参考,这是使用的替代实现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()
Run Code Online (Sandbox Code Playgroud)