【问题标题】:How to run a coroutine twice in Python?如何在 Python 中运行两次协程?
【发布时间】:2020-06-29 16:12:50
【问题描述】:

我有一个包装函数,它可能会运行一个 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 

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

我尝试制作 courutine 的副本,但是使用方法 copy 和 deepcopy 是不可能的。 运行 coroutine 两次的可能解决方案是什么?

【问题讨论】:

  • 我看到了,但它并没有回答我的问题。就我而言,我没有统一的接口如何为异步函数提供参数。在包装器中运行的函数可能有不同的参数。
  • 您可能不希望在对range 的调用中使用1, 。这将导致您进行attempts - 1 尝试。
  • 在这个特定问题中,迭代次数无关紧要

标签: python python-asyncio


【解决方案1】:

正如您已经发现的那样,您不能多次等待协程。这根本没有意义,协程不是函数。

看来您真正想做的是用任意参数重试异步函数调用。您可以使用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)

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多