Comment compiler et configurer automatiquement un paquet ROS dans un sous-répertoire depuis un fichier launch

Cet exemple montre comment exécuter colcon build (si nécessaire) sur un paquet ROS dans un sous-répertoire, et l’ajouter à l’AMENT_PREFIX_PATH pour le lancement courant.

Dans cet exemple, nous utiliserons franka_description comme paquet à compiler :

Fichier de bibliothèque : ros_autobuild.py :

ros_autobuild.py
import subprocess
import os.path

def autobuild_and_setup_ros_package(package_name, package_path):
    # Si [package]/install n'existe pas, exécuter colcon_build là
    install_path = os.path.join(package_path, "install")
    if not os.path.exists(os.path.join(package_path, "install")):
        print(
            f"{package_path}/install does not exist. Running 'colcon build' in {package_path}"
        )
        subprocess.run(["colcon", "build"], cwd=package_path)
    # Préfixer le chemin absolu de [package]/install/[package] à AMENT_PREFIX_PATH
    extra_path = os.path.abspath(os.path.join(install_path, package_name))
    os.environ["AMENT_PREFIX_PATH"] = extra_path + os.pathsep + os.environ.get("AMENT_PREFIX_PATH", "")

Dans votre fichier launch, voici comment l’utiliser :

example_generate_launch.py
import ros_autobuild

def generate_launch_description():
  ros_autobuild.autobuild_and_setup_ros_package(
    "franka_description",
    # Exemple : dossier franka_description dans le même répertoire
    os.path.join(os.path.dirname(__file__), "franka_description")
  )
  # [...] Le reste de votre fichier launch

Check out similar posts by category: ROS, Python