import rospy from std_msgs.msg import String def 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 # name 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()添加详细注释
时间: 2024-03-26 22:42:02 浏览: 187
这是一个ROS(机器人操作系统)的Python程序,用于订阅名为"chatter"的主题,并在接收到消息时调用回调函数"callback"。
具体注释如下:
```
import rospy # 导入ROS的Python库
from std_msgs.msg import String # 导入ROS的标准消息类型String
def callback(data): # 定义回调函数,data为接收到的消息对象
rospy.loginfo(rospy.get_caller_id() + 'I heard %s', data.data) # 打印消息内容
def listener(): # 定义订阅函数
rospy.init_node('listener', anonymous=True) # 初始化ROS节点,指定节点名称为"listener",并设置为匿名节点
rospy.Subscriber('chatter', String, callback) # 订阅名为"chatter"的主题,消息类型为String,回调函数为callback
rospy.spin() # 进入循环,等待消息到达并调用回调函数
if __name__ == '__main__':
listener() # 程序入口,调用listener()函数
```
其中,"rospy.loginfo()"用于打印日志信息,"rospy.get_caller_id()"获取当前节点的名称,"rospy.init_node()"用于初始化ROS节点,"rospy.Subscriber()"用于订阅主题,"rospy.spin()"用于进入循环。
阅读全文