Create a ROS 2 package (Python)


Software in ROS 2 is organized in packages. The goal of these packages is to provide useful functionality. Take into account that the packages should be functionality, but not too much than other software can use it. A ROS 2 package is simply a directory.

This tutorial show how to create a ROS 2 package in Python. For considering a valid package must meet a few requirements

  • The package should contain a file named package.xml
    • Provides meta information about the package
  • The package should contain a file named setup.py
    • Provide information about the package

A ROS 2 package have the next structure:

src/
  my_package/
      setup.py
      package.xml

cd ~/ros2_ws/src/ros2
mkdir testpackage
cd testpackage

Checkout the name label. Should be named as the folder

from setuptools import setup

setup(
    name='testpackage',
    version='0.0.0',
    packages=[],
    py_modules=[],
    install_requires=['setuptools'],
    author='Esteve Fernandez',
    author_email='esteve@osrfoundation.org',
    maintainer='Esteve Fernandez',
    maintainer_email='esteve@osrfoundation.org',
    keywords=['ROS'],
    classifiers=[
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python',
        'Topic :: Software Development',
    ],
    description='Package containing examples of how to use the rclpy API.',
    license='Apache License, Version 2.0',
    test_suite='test',
    entry_points={
        'console_scripts': [
            'listener_py = listener_py:main',
            'talker_py = talker_py:main',
        ],
    },
)

Checkout the name label. Should be named as the folder

<?xml version="1.0"?>
<package format="2">
  <name>testpackage</name>
  <version>0.0.0</version>
  <description>Package containing examples of how to use the rclpy API.</description>
  <maintainer email="esteve@osrfoundation.org">Esteve Fernandez</maintainer>
  <license>Apache License 2.0</license>

  <exec_depend>rclpy</exec_depend>
  <exec_depend>std_msgs</exec_depend>

  <test_depend>ament_copyright</test_depend>
  <test_depend>ament_pep257</test_depend>
  <test_depend>ament_pep8</test_depend>
  <test_depend>ament_pyflakes</test_depend>
  <test_depend>rclpy</test_depend>
  <test_depend>std_msgs</test_depend>

  <export>
    <build_type>ament_python</build_type>
  </export>
</package>

With this command you are going to build only the package: testpackage

cd ~/ros2_ws
ament build --symlink-install --only-package testpackage

Do you need more computing capacity in your robots? Stay tuned