小编And*_*ert的帖子

使用 Python asyncio 从同步函数中运行并等待异步函数

在我的代码中,我有一个带有属性的类,偶尔需要运行异步代码。有时我需要从异步函数访问属性,有时从同步函数访问属性 - 这就是为什么我不希望我的属性是异步的。此外,我的印象是异步属性通常是一种代码异味。如果我错了纠正我。

我在从同步属性执行异步方法并阻止进一步执行直到异步方法完成时遇到问题。

这是一个示例代码:

import asyncio


async def main():
    print('entering main')
    synchronous_property()
    print('exiting main')


def synchronous_property():
    print('entering synchronous_property')
    loop = asyncio.get_event_loop()
    try:
        # this will raise an exception, so I catch it and ignore
        loop.run_until_complete(asynchronous())
    except RuntimeError:
        pass
    print('exiting synchronous_property')


async def asynchronous():
    print('entering asynchronous')
    print('exiting asynchronous')


asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

它的输出:

entering main
entering synchronous_property
exiting synchronous_property
exiting main
entering asynchronous
exiting asynchronous
Run Code Online (Sandbox Code Playgroud)

首先,RuntimeError捕获似乎是错误的,但如果我不这样做,我会得到RuntimeError: This event loop is already running例外。

其次,asynchronous()函数最后执行,同步完成后。我想通过异步方法对数据集进行一些处理,所以我需要等待它完成。如果我await asyncio.sleep(0)在调用之后添加synchronous_property() …

asynchronous python-3.x python-asyncio

8
推荐指数
2
解决办法
1万
查看次数

标签 统计

asynchronous ×1

python-3.x ×1

python-asyncio ×1