小编Ale*_*ges的帖子

Python3 如何 asyncio.gather() 部分函数的列表

我正在尝试创建一个可以传递给 asyncio.gather() 的协程列表

但是,当我将它们附加到列表中时,我想将参数附加到这些协程。

下面显示的我当前的方法使用 functools.partial。不幸的是 asyncio.gather 不接受部分函数,​​这是有道理的。

对我来说没有意义的是如何找到解决方案。

示例代码:

async def test(arg1):
    print(arg1)

statements = []

function = functools.partial(test, "hello world")
statements.append(function)

results = await asyncio.gather(*statements)
Run Code Online (Sandbox Code Playgroud)

那么如何将参数附加到函数,以便它仍然可以传递给 asyncio.gather?

*编辑

看来我是比较傻了。

我的解决方案相当简单,不要使用 functools.partial,只需将协程直接附加到列表中即可。

代码:

async def test(arg1):
    print(arg1)

async def main():
    statements = []
    statements.append(test("hello_world"))
    results = await asyncio.gather(*statements)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)

python-3.x python-asyncio

17
推荐指数
2
解决办法
2万
查看次数

标签 统计

python-3.x ×1

python-asyncio ×1