Passing arguments to launch file via programming

Hi all,

I am learning ros 2 navigation with turtlebot3. When I run the navigation node, I can pass the map to the launch file by using this command line :

ros2 launch turtlebot3_navigation2 navigation2.launch.py map:=~/ros2/src/multithreading_odom/map/map.yaml

How can I pass this map directory to the navigation 2 launch file via programming?

Bellow is my program:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os

from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration

def generate_launch_description():

    turtlebot3_launch = get_package_share_directory('turtlebot3_navigation2')

    map_dir = get_package_share_directory('multithreading_odom'), 'map', 'map.yaml'))

    # how can I pass map_dir to navigation2.launch.py ?
    start_rviz = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(
            os.path.join(turtlebot3_launch, 'launch', 'navigation2.launch.py'),
    )

    return LaunchDescription([
        start_rviz,

    ])

Please help

Thanks,
Thank Vinh

Hello @ThanhVinhCE,

you have to declare a variable that holds the route to your map, like so:

map_file = "~/ros2/src/multithreading_odom/map/map.yaml"

and then pass it inside the launch_arguments dictionary like shown below:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os

from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration

def generate_launch_description():

    turtlebot3_launch = get_package_share_directory('turtlebot3_navigation2')

    map_file = "~/ros2/src/multithreading_odom/map/map.yaml"


    start_rviz = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(
            os.path.join(turtlebot3_launch, 'launch', 'navigation2.launch.py'),
        launch_arguments = {'map_file': map_file}.items()
    )

    return LaunchDescription([
        start_rviz,

    ])

In your other launch file you have to define a corresponding launch configuration:
map_file = LaunchConfiguration('map_file')
It is used to store the value of the launch argument in a variables and to use it in any part of the launch description.

Here is the documentation: Using substitutions — ROS 2 Documentation: Galactic documentation

Hope this helps,

Roberto

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