gpt4 book ai didi

python - 如何等待对象改变状态

转载 作者:太空狗 更新时间:2023-10-30 02:16:18 24 4
gpt4 key购买 nike

在我的 async 处理程序中,我想等到任务的状态发生变化。现在,我只是在无限循环中检查状态并等待。这是一个示例,wait_until_done 函数:

import asyncio


class LongTask:
state = 'PENDING'

my_task = LongTask()


def done():
my_task.state = 'DONE'

async def wait_until_done():
while True:
if my_task.state == 'PENDING':
await asyncio.sleep(2)
else:
break
print("Finally, the task is done")


def main(loop, *args, **kwargs):
asyncio.ensure_future(wait_until_done())
loop.call_later(delay=5, callback=done)

loop = asyncio.get_event_loop()
main(loop)
loop.run_forever()

有更好的方法吗?

最佳答案

为了避免混淆:我猜你不是在谈论 asyncio.Task ,而是一些变量状态,对吧?

在这种情况下,您有 Futuresynchronization primitives这使您可以等待异步更改的某些内容。

如果需要在两种状态之间切换,asyncio.Event可能是你想要的。这是一个小例子:

import asyncio


my_task = asyncio.Event()


def done():
my_task.set()



async def wait_until_done():
await my_task.wait() # await until event would be .set()
print("Finally, the task is done")


async def main():
loop.call_later(delay=5, callback=done)
await wait_until_done()


loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()

更新:

保持 LongTask 接口(interface)的更复杂的例子:

import asyncio



class LongTask:
_event = asyncio.Event()

@property
def state(self):
return 'PENDING' if not type(self)._event.is_set() else 'DONE'

@state.setter
def state(self, val):
if val == 'PENDING':
type(self)._event.clear()
elif val == 'DONE':
type(self)._event.set()
else:
raise ValueError('Bad state value.')

async def is_done(self):
return (await type(self)._event.wait())

my_task = LongTask()


def done():
my_task.state = 'DONE'



async def wait_until_done():
await my_task.is_done()
print("Finally, the task is done")


async def main():
loop.call_later(delay=5, callback=done)
await wait_until_done()


loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()

关于python - 如何等待对象改变状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44891761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com