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

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()

我正在尝试使用 python3 的新库 asyncio。但我收到此错误,不知道为什么。任何帮助将不胜感激。

您遇到的特定错误是因为您试图将 asyncio.as_completed 的 return 值传递给 run_until_completerun_until_complete 期望 FutureTask,但 as_completed return 是迭代器。将其替换为 asyncio.wait,其中 return 是 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()