首页 > 解决方案 > Python - 从同步函数运行协程

问题描述

我想在 中运行协程__init__,我asyncio.create_task用来在非异步函数(即__init__)中启动协程的执行以设置实例属性。我需要等待第一个任务完成才能从__init__. 我无法await在. __init___task.done()__init__

这是一个简单的例子:

async def coro():
    await asyncio.sleep(2)
    return 2
 
class Foo:
    def __init__(self):
        self._job_id_task = asyncio.create_task(coro()) #Starts running coro()
        while not self._job_1_task.done():
            pass
        self.job_id = self._job_id_task.result()

foo = Foo() #gets hung and never returns Foo object.

根据我上面的示例代码,我希望在 2 秒多一点的时间内foo = Foo()创建Foo对象,但是在线执行foo = Foo()被挂起并且永远不会完成。

标签: pythonpython-asyncio

解决方案


您的程序卡住了,因为您没有运行事件循环。您可以像这样在另一个线程中运行事件循环:

import asyncio
from threading import Thread

async def coro():
    await asyncio.sleep(2)
    return 2

def run_loop_in_thread(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()

loop = asyncio.get_event_loop()
coro_thread = Thread(target=run_loop_in_thread, args=(loop,))
coro_thread.start()

class Foo:
    def __init__(self):
        future = asyncio.run_coroutine_threadsafe(coro(), loop)
        self.job_id = future.result()

foo = Foo()

推荐阅读