假设我们有一个虚拟函数:

async def foo(arg):
    result = await some_remote_call(arg)
    return result.upper()

这两者的区别是什么:

import asyncio    

coros = []
for i in range(5):
    coros.append(foo(i))

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(coros))

以及:

import asyncio

futures = []
for i in range(5):
    futures.append(asyncio.ensure_future(foo(i)))

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(futures))

Note:示例返回一个结果,但这不是问题的重点.当返回值很重要时,使用gather()而不是wait().

不管返回值是多少,我都在寻找ensure_future()的清晰性.wait(coros)wait(futures)都运行协同程序,那么什么时候以及为什么要在ensure_future中包装协同程序呢?

基本上,使用Python 3.5的async运行一系列非阻塞操作的正确方法(tm)是什么?

为了获得额外的积分,如果我想成批打电话怎么办?例如,我需要拨打some_remote_call(...)-some_remote_call(...)0次电话,但我不想同时连接some_remote_call(...)0个网络服务器/数据库等.这在线程或进程池中是可行的,但有没有办法在asyncio中做到这一点?

2020 update (Python 3.7+):不要使用这些片段.而是使用:

import asyncio

async def do_something_async():
    tasks = []
    for i in range(5):
        tasks.append(asyncio.create_task(foo(i)))
    await asyncio.gather(*tasks)

def do_something():
    asyncio.run(do_something_async)

还考虑使用Trio,一个强大的第三方替代AsiCIO.

推荐答案

文森特的一条 comments 链接到了https://github.com/python/asyncio/blob/master/asyncio/tasks.py#L346,这表明wait()为您将协同程序包装在ensure_future()中!

换言之,我们确实需要一个future ,而合作项目将悄silent息地转化为future .

当我找到一个关于如何批处理协同计划/future 的明确解释时,我会更新这个答案.

Python-3.x相关问答推荐

这是重命名极地df列的最好方式吗?

如何使用Python将嵌套的XML转换为CSV

谁能解释一下这个带邮编的多功能环路?

如何将 OLS 趋势线添加到使用 updatemenus 显示数据子集的 plotly 散点图图形对象?

如何在pyspark的列中按连续1分组并保持具有特定大小的组

如何知道Pandas 列中的每个后续值是否都大于前面的值? Python相关

Einsum 对于张量乘法很慢

使用正确的数据类型时,使用 Cerberus 验证 JSON 架构会引发错误

每个数据行中每个数据帧值的总和

为什么不切换到 Python 3.x?

numpy.ndarray 与 pandas.DataFrame

在 Python 3 中使用 unittest.mock 修补 input()

使用 Python3 与 HDFS 交互的最佳模块是什么?

迭代器也是可迭代的吗?

Python中的多行日志(log)记录

python 内置的 __exit__ 参数类型是什么?

tkinter TclError:错误的文件类型使用 askopenfilename

为 Python 3 和 PyQt 构建可执行文件

Windows 下 Python 3.x 的 OpenCV

十六进制字符串到 Python 3.2 中的带符号整数?