python - 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()
被挂起并且永远不会完成。
解决方案
您的程序卡住了,因为您没有运行事件循环。您可以像这样在另一个线程中运行事件循环:
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()
推荐阅读
- elasticsearch - Elasticsearch 发布文件: FORBIDDEN/12/index 只读/允许删除(api)]
- birt - Ol start 在 birt 中不起作用
- css - 高度中的 CSS 按钮,带有 flexbox
- java - 输入已更新到数据库中的错误字段
- flutter - Flutter:如果数据为空,FutureBuilder 不会更新
- google-smart-home - 如何对 types.SHUTTER 进行分组,例如 types.LIGHT
- gdb - 时间表休息(
) gdb 调试功能不工作 - java - 将字符串转换为枚举以启用要读取的文件
- c# - 进程(outlook)启动时显示消息
- domain-driven-design - 谁以及如何处理重播事件?