如何在Python中运行两次协同程序?

2024-09-30 02:29:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包装器函数,它可能会运行courutine多次:

async def _request_wraper(self, courutine, attempts=5):
   for i in range(1, attempts):
      try:
         task_result = await asyncio.ensure_future(courutine)
         return task_result
      except SOME_ERRORS:
         do_smth()
         continue 

Corutine可以从不同的异步func创建,它可以接受不同数量的必要/不必要的参数。 当我进行第二次循环迭代时,会出现错误-->;无法重用已等待的协同程序

我曾试图复制courutine,但使用方法copy和deepcopy是不可能的。 运行两次corutine可能的解决方案是什么


Tags: 函数inselffortaskasyncrequestdef
1条回答
网友
1楼 · 发布于 2024-09-30 02:29:01

正如你已经发现的,你不能等待一个合作项目很多次。这根本没有意义,协同程序不是函数

看起来您真正想要做的是用任意参数重试异步函数调用。您可以使用arbitrary argument lists*args)和等价的关键字参数(**kwargs)捕获所有参数并将它们传递给函数

async def retry(async_function, *args, **kwargs, attempts=5):
  for i in range(attempts):
    try:
      return await async_function(*args, **kwargs)
    except Exception:
      pass  # (you should probably handle the error here instead of ignoring it)

相关问题 更多 >

    热门问题