解决ROSPY没有spinOnce

来源:互联网 发布:体彩开奖网络视频直播 编辑:程序博客网 时间:2024/06/05 19:03

之前ROS编程一直用C++,C++订阅消息的时候可以用spin(一直进入回调函数),大循环中用spinOnce时才进入回调函数。最近想显示一个图像界面,python中有matplot模块可以直接figure图像。找到一个最简单的话题订阅程序:

#!/usr/bin/env pythonimport rospyfrom std_msgs.msg import Stringdef callback(data):    rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)def listener():    # In ROS, nodes are uniquely named. If two nodes with the same    # node are launched, the previous one is kicked off. The    # anonymous=True flag means that rospy will choose a unique    # name for our 'listener' node so that multiple listeners can    # run simultaneously.    rospy.init_node('listener', anonymous=True)    rospy.Subscriber("chatter", String, callback)    # spin() simply keeps python from exiting until this node is stopped    rospy.spin()if __name__ == '__main__':    listener()

改为两线程程序:

#!/usr/bin/env pythonimport rospyfrom std_msgs.msg import Stringdef callback(data):    rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)def listener():    # In ROS, nodes are uniquely named. If two nodes with the same    # node are launched, the previous one is kicked off. The    # anonymous=True flag means that rospy will choose a unique    # name for our 'listener' node so that multiple listeners can    # run simultaneously.    rospy.init_node('listener', anonymous=True)    rospy.Subscriber("chatter", String, callback)    #这里加一个while循环就行    while(1):        #此处添加另外一个线程的代码    # spin() simply keeps python from exiting until this node is stopped    rospy.spin()if __name__ == '__main__':    listener()

rospy.spin()作用是当节点停止时让python程序退出,显然和C++ spin的作用不同。

官方的解释:The final addition, rospy.spin() simply keeps your node from exiting until the node has been shutdown. Unlike roscpp, rospy.spin() does not affect the subscriber callback functions, as those have their own threads.

0 0
原创粉丝点击