之前ROS編程一直用C++,C++訂閱消息的時(shí)候可以用spin(一直進(jìn)入回調(diào)函數(shù)),大循環(huán)中用spinOnce時(shí)才進(jìn)入回調(diào)函數(shù)。最近想顯示一個(gè)圖像界面,python中有matplot模塊可以直接figure圖像。找到一個(gè)最簡(jiǎn)單的話題訂閱程序:
#!/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) #這里加一個(gè)while循環(huán)就行 while(1): #此處添加另外一個(gè)線程的代碼 # spin() simply keeps python from exiting until this node is stopped rospy.spin()if __name__ == '__main__': listener()rospy.spin()作用是當(dāng)節(jié)點(diǎn)停止時(shí)讓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.
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注