假设我们有一个虚拟函数:
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.