Skip to content

Creating a Python node in ROS

Nathan Collins edited this page Apr 28, 2018 · 3 revisions

Create the Package

Commands

catkin_create_pkg <node_name> <dependencies>
# for example
catkin_create_pkg relay_board rospy std_msgs bruin2_msgs

I strongly recommend using those three dependencies for new packages. Create all msg files in bruin2_msgs to simplify things.

Alterations

You must create a file setup.py in the root of the new package with the following contents:

## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD

from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

# fetch values from package.xml
setup_args = generate_distutils_setup(
    packages=['<package_name>'], # Change this line; for example 'relay_board'
    package_dir={'': 'src'},
)

setup(**setup_args)

You must also uncomment this line in CMakeLists.txt:
catkin_python_setup()
It should be about line 23

Write your Code

You'll want a package inside the src folder that contains a main.py. For example: src > relay_board > main.py. Note that the main.py must be marked executable and contain the #!/usr/bin/env python line.

Importing Messages

from bruin2_msgs.msg import <MsgName>

Publishers

pub = rospy.Publisher("<TopicName>", <MsgName>, queue_size=10)
pub.publish(<MsgName>(arg1, arg2, . . . ))
# or
pub.publish(arg1, arg2, . . . )
# where arg1, arg2, . . . are the variables defined by the msg file

Subscribers

rospy.Subscriber("<TopicName>", <MsgName>, callbackFunction)

Clone this wiki locally