It is also explained here that writing ROS function packages in Python also requires CMakelists.txt
Retrieved from: https://blog.csdn.net/u013832707/article/details/53980759
Implement ROS node with Python
Lasting determination 2017-01-02 18:28:59 21390 Collection 24
Category column: ROS Python Article tags: python ROS
copyright
The main programming language of ROS is not only C++, but also Python. Here is an explanation of how to use Python to write ROS nodes. For tutorials, refer to the official website rospy_tutorials .
1. Write a simple publisher and subscriber
1Create a workspace
Create a folder hello_rospy, then create a subdirectory src in this directory, cd to the src directory, and run the following command to create a work package
catkin_create_pkg beginner_tutorials std_msgs rospy roscpp
cd to the upper directory of src, compile and source
cd ..
catkin_make
. devel/setup.bash
2 write publisher program and subscriber program
roscd beginner_tutorials/
mkdir scripts
cd scripts
Create a new talker.py file in the scripts directory and fill in the following content:
#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String
def talker():
pub = rospy.Publisher('chatter', String, queue_size=10)
rospy.init_node('talker', 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:
talker()
except rospy.ROSInterruptException:
pass
Create a new listener.py file in the scripts directory and fill in the following content:
#!/usr/bin/env python
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
# 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()
Remember to change the permissions to executable files
3. Compile
Modify Cmakelist.txt as follows:
cmake_minimum_required(VERSION 2.8.3)
project(beginner_tutorials)
## Find catkin macros and libraries
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
)
catkin_package()
Just run it directly in the workspace catkin_make
.
4. Run
Execute the following commands in the 3 terminals respectively
roscore
rosrun beginner_tutorials talker.py
rosrun beginner_tutorials listener.py
The results are as follows: