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()
我正在尝试使用 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()
关于python - 为什么我在尝试使用 asyncio 时得到 "RuntimeError: yield was used instead of yield from for generator in task Task"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28372294/