Skip to content

Creating a ROS Package that uses Python Scripts

Federico Pizarro Bejarano edited this page Nov 14, 2019 · 12 revisions

Setting up a package that depends on rospy

Written by: Federico Pizarro Bejarano

Here we will be creating a ROS package that depends on rospy. Our package will print out a message to the screen. This is based off this tutorial, although it has been simplified: http://wiki.ros.org/rospy_tutorials/Tutorials/Makefile

Setting up the package and structure

Run these commands in your workspace to create the package and create the necessary structure.

$ cd ~/catkin_ws/src
$ catkin_create_pkg my_pkg rospy #add other dependencies here
$ cd my_pkg    # new catkin package, in the workspace
$ mkdir bin
$ mkdir src
$ mkdir src/tutorial_package #this will be our python package
$ touch src/tutorial_package/__init__.py

The __init__.py is empty but it is necessary as it makes python recognize the folder as a python package.

Creating our Python code

Now lets create our python function. Make a file in tutorial_package called hello.py and type in the following:

def say(name):
    print('Hello ' + name)

To create the executable first create the file hello (no extension) in the bin folder and put in:

#! /usr/bin/env python

import tutorial_package.hello


if __name__ == '__main__':
    tutorial_package.hello.say('my friend!')

The first line is the shebang needed for the executable to be recognized as python. Next is the main statement. Make this file an executable by running chmod u+x bin/hello.

Creating and modifying necessary files

Now in ~/catkin_ws/src/my_pkg create the file setup.py and put in:

## ! 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=['tutorial_package'],
    package_dir={'': 'src'},
)

setup(**setup_args)

This file is needed to for the ROS package to work.

Now, replace your CMakeLists.txt with:

cmake_minimum_required(VERSION 2.8.3)
project(my_pkg)

find_package(catkin REQUIRED COMPONENTS
  rospy
)

catkin_python_setup()
catkin_install_python(PROGRAMS bin/hello DESTINATION ${PROJECT_NAME}/bin)

If there are any different dependencies than the ones used in this tutorial, they will need to be here inside of find_package.

Compiling and running

Now return to the workspace and enter:

$ cd ~/catkin_ws
$ catkin_make
$ . devel/setup.bash  # only needed when the directory structure changes

If everything works well, you can run:

$ rosrun my_pkg hello

Now you should see Hello my friend!

Clone this wiki locally