python - 如何运行协程而不等待它?

标签 python python-asyncio

我有一个非异步函数,如下所示:

def do_stuff(on_finished):
    result = # complicated calculations here
    on_finished(result)

我传入的回调看起来或多或少像这样:

async def on_finished(self, result):
    response = await post_over_http(result)
    self.last_status = response.status 

当我调用do_stuff时,我想要发生的是这样的:

  1. do_stuff 执行并调用 on_finished
  2. on_finished 执行,通过 HTTP 发布结果,然后立即返回。
  3. do_stuff 现在立即返回。
  4. 稍后,HTTP 响应返回,执行返回到 on_finished 的第二行。

重要的是,我不希望 do_stuff 是异步的。出于架构原因,我希望将 do_stuff 与网络代码的异步性质隔离,因此我不想仅仅因为使用它的某些代码是异步的而将其设为异步。

在 JavaScript 中这不会有问题 - 基本上将上述代码直接转录为 JavaScript,我将获得所需的行为。 onFinished 将返回一个 Promise,doStuff 不会等待并立即返回,但是当 Promise 稍后解析时,onFinished 的第二行将运行。这在Python中可能吗?我不确定如何实现它。通过上面的代码,我想我只是在 do_stuff 的最后一行创建了一个协程,但从未调用它。

最佳答案

您可以像这样设计您的 do_stuff 函数:

def do_stuff(on_finished):
    async def _do_complicated_calculation():
        result = # do the calculation here & the post request
        await on_finished(result)
    asyncio.ensure_future(_do_complicated_calculation())
    return "ok"

当您调用do_stuff(...)时,复杂的计算将被添加到asyncio事件循环中,因此它会异步执行。如果您不打算在主线程中启动事件循环,则应该让事件循环在不同的线程中运行。

由于 _do_complicated_calculation() 是异步的,do_stuff 将首先返回 "ok",在计算完成后,on_finished(...) 正在被调用。

关于python - 如何运行协程而不等待它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57624752/

相关文章:

python - 如何通过ffmpeg-python获取service_name和程序列表

python - 如何将经过训练的卷积网络(CNN)转换为检测器?

python - 如何禁用pylint msg "too many local variables"

python - 如何在 Python 中对角化稀疏 csr 一维矩阵(向量)?

尽管传输存在,但 Python AsyncIO 由于缺少传输而无法创建协议(protocol)

python - 根据参数使函数异步

python - 循环行并将数据打印到新数据框

python - 将 Aiohttp 与代理一起使用

python - 在新线程中启动异步函数