如何在 python 3.8+ 中将函数转换为协程

Leg*_*ooj 2 python asynchronous python-3.x python-asyncio

正如这个问题中所述,我们可以使用装饰器asyncio.coroutine将函数转换为协程,如下所示:

def hello():
    print('Hello World!')

async_hello = asyncio.coroutine(hello)
Run Code Online (Sandbox Code Playgroud)

然而,从 python 3.8 开始,这个函数已被弃用(由 替代async def ...)。那么我们如何在 3.8+ 中做到这一点而不需要呢async def ...

Mis*_*agi 6

定义一个仅调用该函数的自定义协程包装器:

from functools import wraps

def awaitify(sync_func):
    """Wrap a synchronous callable to allow ``await``'ing it"""
    @wraps(sync_func)
    async def async_func(*args, **kwargs):
        return sync_func(*args, **kwargs)
    return async_func
Run Code Online (Sandbox Code Playgroud)

这可用于使任意同步函数兼容任何需要协程的地方。

def hello():
    print('Hello World!')

async_hello = awaitify(hello)
asyncio.run(async_hello())  # Hello World!
Run Code Online (Sandbox Code Playgroud)