ROS2 Python Package Convention

Is the following the ROS2 python package convention?
Put modules that you want to import in a folder with the same name as the package, and put ros nodes/py scripts in a script folder? In this case, what changes do I need to make to the following setup.py file to create an executable out of the my_script.py file that is in the scripts folder?

import os
from glob import glob

from setuptools import setup

package_name = "my_package"

setup(
    name=package_name,
    version="0.0.0",
    packages=[package_name],
    data_files=[
        ("share/ament_index/resource_index/packages", ["resource/" + package_name]),
        ("share/" + package_name, ["package.xml"]),
    ],
    install_requires=["setuptools"],
    zip_safe=True,
    maintainer="maintainer_name",
    maintainer_email="maintainer_email@email.com",
    description="TODO: Package description",
    license="TODO: License declaration",
    tests_require=["pytest"],
    entry_points={
        "console_scripts": [
            "my_script= my_package.my_script:main"
        ]
    },
)

When you create a package, a second sub-directory the same name as your package gets created. So something like:
my_pkg/my_pkg/

You can put your scripts in there, next to that the python file

For the executable, this is the logic in console_scripts:

[name of executable] = [name of package].[name of file]:main

If you add a directory /scripts, then you wouldn’t need to add it there, at least I don’t think so.

Hi @roalgoal , for clarification, I would like to create an executable out of a script that resides in the scripts folder. However, if I leave setup.py the way it is in my first post then, colcon compiles the package without any complaints. However, when I ros2 run the executable then, it says it can’t find the module named my_package.my_script. What am I doing wrong? Also, FYI, I’m using the ament_python system and not ament_cmake_python.

I was able to resolve this issue today. So this is useful for future readers, the solution is to specify the scripts folder as a python package and also state the entry point referencing the scripts folder as follows:
packages=[package_name, 'scripts'],

entry_points={
        "console_scripts": [
            "my_script= scripts.my_script:main"
        ]

@roalgoal , thanks for your help!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.