如何从 launch 文件自动构建和设置子目录中的 ROS 包

此示例展示了如何 colcon build(如果需要)子目录中的 ROS 包,并将其添加到当前 launch 的 AMENT_PREFIX_PATH 中。

在此示例中,我们将使用 franka_description 作为要构建的包:

库文件:ros_autobuild.py

ros_autobuild.py
import subprocess
import os.path

def autobuild_and_setup_ros_package(package_name, package_path):
    # If [package]/install does not exist, run colcon_build there
    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)
    # Preprend absolute path of [package]/install/[package] to 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", "")

在你的 launch 文件中,以下是如何使用它:

example_generate_launch.py
import ros_autobuild

def generate_launch_description():
  ros_autobuild.autobuild_and_setup_ros_package(
    "franka_description",
    # Example: franka_description folder in the same directory
    os.path.join(os.path.dirname(__file__), "franka_description")
  )
  # [...] The rest of your launch file

Check out similar posts by category: ROS, Python