简体   繁体   English

如何使用asyncio处理闭包

[英]How to handle Closures with asyncio

I'm trying to do some asynchronous messaging for a controller project that I'm doing, and the goal of the following function is to return a callback to an appjar app.registerEvent call, which will update the status section of the motor control UI. 我正在尝试为正在执行的控制器项目做一些异步消息传递,并且以下功能的目标是将回调返回到appjar app.registerEvent调用,该调用将更新电机控制UI的状态部分。

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()

However, this doesn't work, as when I do app.registerEvent(motorStatusMonitor(event_loop, app, Messenger)) it just hangs forever. 但是,这不起作用,因为当我执行app.registerEvent(motorStatusMonitor(event_loop, app, Messenger))它将永远挂起。

How should I actually be going about implementing async here? 我实际上应该如何在这里实现异步?

Full code for everything is at Github . 一切的完整代码在Github上

This: 这个:

loop.run_until_complete(future)

Is waiting the for the future to complete which it never does. 等待着永远完成的未来。

Also you must not call future.result() but instead something like await future which will return the result. 另外,您一定不要调用future.result() ,而应该await future ,它会返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM