【发布时间】:2018-07-13 15:59:59
【问题描述】:
我正在尝试弄清楚如何使用 rospy actionlib 和 asyncio
异步等待操作结果。为此我尝试了
编写一个动作执行生成器,但现在还没有成功。
我的想法是为动作的done_callback 添加一个 asyncio 未来
但未来似乎永远不会结束。
代码在这里:
def _generate_action_executor(self, action):
async def run_action(goal):
action_done = asyncio.Future()
def done_callback(goal_status, result, future):
status = ActionLibGoalStatus(goal_status)
print('Action Done: {}'.format(status))
future.set_result(result)
action.send_goal(goal,
lambda x, y: done_callback(x,
y,
action_done))
try:
result = await action_done
#problem future never done
except asyncio.CancelledError as exc:
action.cancel()
raise exc
return result
return run_action
async def do_some_other_stuff(action):
//do stuff
my_goal = MyActionRequest('just do it')
run_action = self._generate_action_executor(action)
response = await run_action(my_goal)
return response
if __name__ == "__main__":
action = actionlib.SimpleActionClient('my_action',
MyAction)
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(do_some_other_stuff(action))
finally:
loop.close()
【问题讨论】:
-
回调是否在另一个线程中运行?如果是,您必须使用loop.call_soon_threadsafe,例如
loop.call_soon_threadsafe(done_callback, x, y, action_done) -
是的,它被另一个线程调用。怎么比就等着呢?
-
嗨文森特我对你的回答有点困惑。使用 loop.call_soon_threadsafe 事件循环将调用 done_callback 对吗?但在我的情况下,该操作将调用回调。唯一的问题是我不知道如何正确注册未来,以便我可以等待它并获得结果。
标签: python-3.x asynchronous python-asyncio rospy