首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python异步运行并等待来自同步函数的异步函数

问使用Python异步运行并等待来自同步函数的异步函数
EN

Stack Overflow用户
提问于 2019-03-13 17:30:08
回答 4查看 18.2K关注 0票数 16

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

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

下面是一个示例代码:

代码语言:javascript
复制
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())

其产出:

代码语言:javascript
复制
entering main
entering synchronous_property
exiting synchronous_property
exiting main
entering asynchronous
exiting asynchronous

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

第二,在同步函数完成后,最后执行asynchronous()函数。我想通过异步方法对数据集做一些处理,所以我需要等待它完成。如果我在调用synchronous_property()之后添加synchronous_property(),它将在main()完成之前调用asynchronous(),但这无助于我。我需要在asynchronous()完成之前运行synchronous_property()。

我遗漏了什么?我在运行python 3.7。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-03-14 19:24:04

Asyncio确实坚持不允许嵌套循环,精心设计。但是,您始终可以在不同的线程中运行另一个事件循环。下面是一个变体,它使用线程池来避免每次创建一个新线程:

代码语言:javascript
复制
import asyncio, concurrent.futures

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

pool = concurrent.futures.ThreadPoolExecutor()

def synchronous_property():
    print('entering synchronous_property')
    result = pool.submit(asyncio.run, asynchronous()).result()
    print('exiting synchronous_property', result)

async def asynchronous():
    print('entering asynchronous')
    await asyncio.sleep(1)
    print('exiting asynchronous')
    return 42

asyncio.run(main())

这段代码在每个同步->异步边界上创建了一个新的事件循环,所以如果您经常这样做,就不要期望高性能。可以通过使用asyncio.new_event_loop创建每个线程的一个事件循环并将其缓存到线程局部变量中来改进它。

票数 15
EN

Stack Overflow用户

发布于 2019-11-29 10:22:09

最简单的方法是使用现有的“轮子”,如同步

代码语言:javascript
复制
from asgiref.sync import async_to_sync

然后:

代码语言:javascript
复制
async_to_sync(main)()

一般而言:

代码语言:javascript
复制
async_to_sync(<your_async_func>)(<.. arguments for async function ..>)

这是一个调用类,它将只在事件循环的线程上工作的可调用类转换为在子线程中工作的同步可调用类。 如果调用堆栈包含异步循环,则代码在那里运行。否则,代码将在新线程中的新循环中运行。 无论哪种方式,该线程然后暂停并等待运行任何使用SyncToAsync从调用堆栈中进一步调用的SyncToAsync代码,最后在异步任务返回后退出。

票数 3
EN

Stack Overflow用户

发布于 2019-07-24 01:54:50

正如所述,这个问题似乎有问题。重申这个问题:如何在线程(不包含异步进程,因此被认为是同步)和异步进程(在某些事件循环中运行)之间进行通信。一种方法是使用两个同步队列。同步进程将其请求/参数放入QtoAsync,并等待QtoSync。异步进程不需要等待就读取QtoAsync,如果它找到请求/参数,则执行请求,并将结果放入QtoSync。

代码语言:javascript
复制
import queue
QtoAsync = queue.Queue()
QtoSync = queue.Queue()
...

async def asyncProc():
    while True:
        try:
            data=QtoAsync.get_nowait()
            result = await <the async that you wish to execute>
            QtoAsync.put(result) #This can block if queue is full. you can use put_nowait and handle the exception.
        except queue.Empty:
            await asyncio.sleep(0.001) #put a nominal delay forcing this to wait in event loop
....
#start the sync process in a different thread here..
asyncio.run(main()) #main invokes the async tasks including the asyncProc

The sync thread puts it request to async using:
req = <the async that you wish to execute>
QtoAsync.put(req)
result = QtoSync.get()

这应该能行。

问题是: 1.当异步进程用asyncio.run (或类似的)执行块启动时,直到异步进程完成为止。调用asyncio.run 2之前必须启动单独的同步线程,通常异步进程依赖于该循环中的其他异步进程。因此,不允许直接从另一个线程调用异步进程。应该使用事件循环进行交互,使用两个队列是一种方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55147976

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档