从同步函数调用异步函数,而同步函数继续:Python [英] Call async function from sync function, while the synchronous function continues : Python

查看:145
本文介绍了从同步函数调用异步函数,而同步函数继续:Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仔细阅读 AsyncIO 和文章上的许多文档后,我仍然找不到答案: 异步运行一个函数(不使用线程),并确保该函数调用此异步功能将继续执行.

After perusing many docs on AsyncIO and articles I still could not find an answer to this : Run a function asynchronously (without using a thread) and also ensure the function calling this async function continues its execution.

伪代码-

async def functionAsync(p):
    #...
    #perform intensive calculations
    #...
    print ("Async loop done")

def functionNormal():
    p = ""
    functionA(p)
    return ("Main loop ended")

 print ("Start Code")
 print functionNormal()

预期输出:

Start code
Main loop ended
Async loop done

搜索了使用 loop.run_until_complete 的示例,但由于它实际上是阻塞的,因此不会返回 functionNormal()的打印值.

Searched examples where loop.run_until_complete is used, but that will not return the print value of functionNormal() as it is blocking in nature.

推荐答案

asyncio 必须在不使用线程的情况下在后台"运行任意代码.正如 user4815162342 所述, asyncio 一样,您运行的事件循环会阻塞主线程并管理协程的执行.

asyncio can't run arbitrary code "in background" without using threads. As user4815162342 noted is asyncio you run event loop that blocks main thread and manages execution of coroutines.

如果要使用 asyncio 并加以利用,则应重写所有使用协程的函数,直到主函数-程序入口点为止都是协程.该主要协程通常传递给 run_until_complete .这篇小帖更详细地揭示了该主题.

If you want to use asyncio and take advantage of using it, you should rewrite all your functions that uses coroutines to be coroutines either up to main function - entry point of your program. This main coroutine is usually passed to run_until_complete. This little post reveals this topic in more detail.

由于您对Flask感兴趣,因此请查看 Quart :这是一个Web框架尝试根据 asyncio 实现Flask API(尽可能多地实现).该项目存在的原因是因为纯Flask与 asyncio 不兼容.Quart被编写为兼容.

Since you're interested in Flask, take a look Quart: it's a web framework that tries to implement Flask API (as much as it's possible) in terms of asyncio. Reason this project exists is because pure Flask isn't compatible with asyncio. Quart is written to be compatible.

如果您希望使用纯Flask,但又需要异步处理,请查看 gevent .通过猴子补丁,它可以使您的代码异步.尽管此解决方案有其自身的问题(创建 asyncio 的原因).

If you want to stay with pure Flask, but have asynchronous stuff, take a look at gevent. Through monkey-patching it can make your code asynchronous. Although this solution has its own problems (which why asyncio was created).

这篇关于从同步函数调用异步函数,而同步函数继续:Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆