如何使用asynci处理闭包

2024-10-01 04:54:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为我正在做的控制器项目做一些异步消息传递,下面函数的目标是返回一个appjar app.registerEvent调用的回调,它将更新motor control UI的status部分。在

def motorStatusMonitor(loop: aio.AbstractEventLoop, app: aj.appjar.gui, Messenger: cmd.PyCmdMessenger.CmdMessenger)-> Callable:
    async def getStatus(aFuture):
        nonlocal Messenger
        nonlocal app
        # Ask for the current status of the motor
        t = await Control.sendCommand(Messenger, "Status")
        d = {t[1][0]: t[1][1], t[1][2]: t[1][3]}  # parse the response
        def statusChanger():  # need a closure to write to the app when called
            nonlocal d  # use the message from above
            nonlocal app  # use the app passed with motorStatusMonitor
            app.openTab("Main", "Control")
            app.openLabelFrame("Status")
            app.setLabel("motorStatus", f"Motor A: \t\t {get('A', d, '???')}\nMotor B: \t\t {get('B', d, '???')}") # Print the status of the motors to the app
        aFuture.set_result(statusChanger)

    future = aio.Future()
    aio.ensure_future(getStatus(future))
    loop.run_until_complete(future)
    return future.result()

但是,这不起作用,因为当我这样做时,app.registerEvent(motorStatusMonitor(event_loop, app, Messenger))它就永远挂起了。在

我应该如何在这里实现异步?在

所有内容的完整代码都在Github。在


Tags: thetoloopappdefstatusfuturemessenger
1条回答
网友
1楼 · 发布于 2024-10-01 04:54:14

这个:

loop.run_until_complete(future)

是在等待未来的完成,而它从来没有这样做过。在

另外,您不能调用future.result(),而应该调用类似await future的函数来返回结果。在

相关问题 更多 >