我正在尝试创建一个可以传递给 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)