我已经读完了this tutorial个关于异步表的理解.现在我想try 一下异步判决书的理解.以下是要复制的代码:

import asyncio


async def div7_tuple(x):
    return x, x/7


async def main():
    lost = [4, 8, 15, 16, 23, 42]
    awaitables = asyncio.gather(*[div7_tuple(x) for x in lost])
    print({k: v for k, v in awaitables})


if __name__ == '__main__':
    asyncio.run(main())

但是,这会导致一个异常:

> RuntimeError: await wasn't used with future 
> sys:1: RuntimeWarning:coroutine 'div7_tuple' was never awaited

如何用asyncio.gather()美元做到这一点?

奇怪的是,这不适用于以未排序的方式构造未排序的对象,因为如果我try 以一种排序的方式进行try ,它就会起作用:

async def div7(x):
    return x/7


async def main2():
    lost = [4, 8, 15, 16, 23, 42]
    print({k: await v for k, v in [(x, div7(x)) for x in lost]})

推荐答案

gather()返回一个Future对象(this is,错误消息显示为-await wasn't used with future的Future对象).

如果您需要对象的结果(以便对其进行迭代),则需要首先将其设置为await:

async def main():
    lost = [4, 8, 15, 16, 23, 42]
    awaitables = asyncio.gather(*[div7_tuple(x) for x in lost])
    print({k: v for k, v in await awaitables})

或者:

async def main():
    lost = [4, 8, 15, 16, 23, 42]
    awaitables = await asyncio.gather(*[div7_tuple(x) for x in lost])
    print(dict(awaitables))

源代码中的相关代码为here:

    def __await__(self):
        if not self.done():
            self._asyncio_future_blocking = True
            yield self
        if not self.done():
            raise RuntimeError("await wasn't used with future")
        return self.result()  # May raise too.

    __iter__ = __await__  # make compatible with 'yield from'.

That __iter__ = __await__ is what makes it possible to iterate over a Future(and not to get a TypeError instead which says "TypeErr或者: 'Future' object is not iterable") but since you didn't use await to make that Future done(It's result get set) it shows you that error message.

Python相关问答推荐

如何标记Spacy中不包含特定符号的单词?

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

计算组中唯一值的数量

Julia CSV for Python中的等效性Pandas index_col参数

使用groupby Pandas的一些操作

基于索引值的Pandas DataFrame条件填充

将输入聚合到统一词典中

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

有没有一种ONE—LINER的方法给一个框架的每一行一个由整数和字符串组成的唯一id?

如何在图中标记平均点?

当点击tkinter菜单而不是菜单选项时,如何执行命令?

如何在turtle中不使用write()来绘制填充字母(例如OEG)

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

跳过嵌套JSON中的级别并转换为Pandas Rame

如何将数据帧中的timedelta转换为datetime

Tensorflow tokenizer问题.num_words到底做了什么?

多个矩阵的张量积

Python:从目录内的文件导入目录

利用SCIPY沿第一轴对数组进行内插

了解如何让库认识到我具有所需的依赖项