launch功能用于多节点的启动和配置。
在ROS1中,launch文件由XML描述文档实现
在ROS2中,launch文件由python脚本实现;
ROS1中launch文件是XML描述文档,它长这个样子(turtlesim.xml):
<launch>
<node pkg="turtlesim" type="turtlesim_node" name="my_turtle" output="screen" />
<node pkg="turtlesim" type="turtle_teleop_key" name="my_key" output="screen" />
launch>
运行:
roslaunch package_name launch_file_name
eg:
roslaunch turtlesim turtlesim.xml
先看个ROS2自带的launch脚本的例子,
/opt/ros/humble/share/turtlesim/launch$ cat multisim.launch.py
它长这个样子:
from launch import LaunchDescription # launch文件的描述类
from launch_ros.actions import Node # 节点启动的描述类
def generate_launch_description(): # 自动生成launch文件的函数
return LaunchDescription([ # 返回launch文件的描述信息
Node( # 配置一个节点的启动
namespace= "turtlesim1", # 节点名字
package='turtlesim', # 节点所在的功能包
executable='turtlesim_node', # 节点的可执行文件
output='screen', # 在屏幕显示
),
Node( # 配置一个节点的启动
namespace= "turtlesim2", # 节点名字
package='turtlesim', # 节点所在的功能包
executable='turtlesim_node', # 节点的可执行文件
output='screen', # 在屏幕显示
),
])
运行:
ros2 launch turtlesim multisim.launch.py
将会启动两个小海龟
下面是一个测试usb_cam的例子:
/opt/ros/humble/share/usb_cam/launch$ cat demo_launch.py
这个例子演示了,启动两个节点,并且加载了一个保存参数的文件params.yaml
import argparse
import os
import sys
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
ld = LaunchDescription()
parser = argparse.ArgumentParser(description='usb_cam demo')
parser.add_argument('-n', '--node-name', dest='node_name', type=str,
help='name for device', default='usb_cam')
args, unknown = parser.parse_known_args(sys.argv[4:])
usb_cam_dir = get_package_share_directory('usb_cam')
# get path to params file
params_path = os.path.join(
usb_cam_dir,
'config',
'params.yaml'
)
node_name = args.node_name
print(params_path)
ld.add_action(Node(
package='usb_cam', executable='usb_cam_node_exe', output='screen',
name=node_name,
# namespace=ns,
parameters=[params_path]
))
ld.add_action(Node(
package='usb_cam', executable='show_image.py', output='screen',
# namespace=ns,
# arguments=[image_manip_dir + "/data/mosaic.jpg"])
# remappings=[('image_in', 'image_raw')]
))
return ld
启动命令
ros2 launch usb_cam demo_launch.py