如何将上述例子放在两个python文件中来实现 publisher往另外一个文件的subscriber中发布消息,而subscriber则是从另一个文件的publisher中订阅消息
时间: 2024-05-15 18:16:52 浏览: 40
第一个文件publisher.py:
```python
import rospy
from std_msgs.msg import String
def publisher():
pub = rospy.Publisher('topic', String, queue_size=10)
rospy.init_node('publisher', anonymous=True)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
hello_str = "hello world %s" % rospy.get_time()
rospy.loginfo(hello_str)
pub.publish(hello_str)
rate.sleep()
if __name__ == '__main__':
try:
publisher()
except rospy.ROSInterruptException:
pass
```
第二个文件subscriber.py:
```python
import rospy
from std_msgs.msg import String
def callback(data):
rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
def subscriber():
rospy.init_node('subscriber', anonymous=True)
rospy.Subscriber("topic", String, callback)
rospy.spin()
if __name__ == '__main__':
subscriber()
```
在终端中运行以下命令:
```bash
roscore
```
在另一个终端中运行以下命令:
```bash
rosrun PACKAGE_NAME publisher.py
```
在另一个终端中运行以下命令:
```bash
rosrun PACKAGE_NAME subscriber.py
```
publisher将会发布消息,subscriber将会收到并打印出来。
阅读全文