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

标签 python python-3.5 python-asyncio

在我的 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/

相关文章:

python:列出包内的模块

python - 在 Python 的嵌套函数中使用全局变量

unicode - Python 3 UnicodeEncodeError : 'ascii' codec can't encode characters

python - pip3 install pyautogui 失败,错误代码为 1 Mac OS

classification - NLTK 感知器标记器 "TypeError: ' LazySubsequence 对象不支持项目分配”

python - 使用 asyncio 的程序结构

python - 如何在 tensorflow 中将矩阵与间隔连接起来

python - 使 TextInput on_text_validate 事件可从另一个小部件访问

python-3.x - python 3.5+ 中 pycurl 的异步替代方案

Python asyncio,可以等待/产生整个 myFunction()