我正在尝试为我正在执行的控制器项目执行一些异步消息传递,并且以下函数的目标是将回调返回到appjar app.registerEvent
调用,该调用将更新电机控制UI的状态部分。如何使用asyncio处理闭包
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。
如果没有实际的代码显示你在做什么,你会如何期待其他人提供帮助? – Ding
我在提问之前不小心打了提交,这是我的错误。 – nick5435
你想实现什么目标?因为关闭不是问题。至少,你可以重写你的代码,而不是使用闭包,而是使用全局的'app'。我并不是说封闭不是正确的方法(即使它在Python中不是很流行)我在说你可能正在讨论XY问题https://meta.stackexchange.com/questions/66377/what-is -the-XY-问题。试着扩大你想要达到的目标。 – amirouche