2017-07-17 32 views
1

我正在尝试为我正在执行的控制器项目执行一些异步消息传递,并且以下函数的目标是将回调返回到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

+0

如果没有实际的代码显示你在做什么,你会如何期待其他人提供帮助? – Ding

+0

我在提问之前不小心打了提交,这是我的错误。 – nick5435

+0

你想实现什么目标?因为关闭不是问题。至少,你可以重写你的代码,而不是使用闭包,而是使用全局的'app'。我并不是说封闭不是正确的方法(即使它在Python中不是很流行)我在说你可能正在讨论XY问题https://meta.stackexchange.com/questions/66377/what-is -the-XY-问题。试着扩大你想要达到的目标。 – amirouche

回答

0

此:

loop.run_until_complete(future) 

正在等待未来的完成这不可能发生。

此外,您不能拨打future.result(),而是像await future那样会返回结果。

+0

所以在我的函数结束时,我需要返回闭包,我只是'返回等待未来',摆脱'loop.run_until_complete'的调用? – nick5435

+0

此外,我不认为我可以在这里使用'await',因为我没有创建一个coro,所以这个函数特别需要同步。 – nick5435