python - 为什么我在尝试使用 asyncio 时得到 "RuntimeError: yield was used instead of yield from for generator in task Task"?

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

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

最佳答案

您遇到的特定错误是因为您试图将 asyncio.as_completed 的返回值传递给 run_until_completerun_until_complete 需要一个 FutureTask,但 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/

相关文章:

python - 如何在 Linux 上的 Python 中检查文件锁?

python - 在 asyncio 中测试一个永远运行的任务

Python 包文件夹结构

python - 如何使用groupby制作唯一的用户ID级别数据框?

Python 名称错误 : name is not defined (related to having default input argument types)

python - 对行匹配条件的列子集进行排序

python - 按内部数组的特定元素分组

python - 将 csv 读取到 pandas 并按原样保留值

python-3.x - 具有 map&reduce 风格且不会淹没事件循环的异步

python - 如何使用异步请求保存 JSON 响应?