ros2使用python包,通过launch文件加载yaml文件,无法覆盖默认参数的解决办法

首先确保已经创建config、launch文件夹,文件夹下有对应的文件,创建的节点能够通过launch文件正常启动。

解决办法:

  1. 在setup.py文件中,仿照添加launch文件步骤,添加config文件夹

     	# add launch file
        (os.path.join('share', package_name), glob('launch/*launch.[pxy][yma]*')),
        # add config file
        (os.path.join('share', package_name), glob('config/*.[yma]*')),
    
  2. 在launch文件中增加config文件路径,并在节点中使用

    	config = os.path.join(
            get_package_share_directory('test_yaml'),
            # 'config',		把这个config注释掉
            'test_yaml_config.yaml'
        )
    	 Node(
                package='test_yaml',
                ...
                # load param from yaml
                parameters=[config]
            )
    
    

注意:# ‘config’, 把这个config注释掉
因为实际测试发现,在第1步添加config文件夹时,并没有生成文件夹。

  1. 注意yaml文件书写格式

    test_node:	# node name	这里必须填写对应的节点名称,或命名空间(如果有)
    
    # must declare ros__parameters
      ros__parameters:
    
        # test params
        test_param: 0.01
    
  2. 删除之前编译生成的文件夹,然后再重新编译,安装,启动

    rm -rf build/ install/ log/
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ROS 2(Robot Operating System)是一个开源的机器人操作系统,它支持分布式、模块化和异步的系统设计。在ROS 2中,YAML(Yet Another Markup Language)通常用于配置文件,如参数服务器中的参数设置或launch文件中的启动信息。 要从程序内部读取并修改 YAML 文件的内容,你可以使用 Python 库 `rclpy_yaml_param_parser` 和 `yaml` 库。这里是一个简化的步骤: 1. 安装必要的库: ```sh pip install rclpy yaml ``` 2. 在代码中读取 YAML 文件: ```python import yaml from rclpy.node import Node class AppConfigNode(Node): def __init__(self): super().__init__('app_config_node') self.config_file = 'config.yaml' with open(self.config_file, 'r') as stream: try: self.config_data = yaml.safe_load(stream) except yaml.YAMLError as exc: self.get_logger().error('Failed to load config file: %s', str(exc)) # 在节点初始化后,你可以访问 config_data 变量 ``` 3. 修改 YAML 内容: ```python def update_config_value(key, new_value): if key in self.config_data: self.config_data[key] = new_value else: self.get_logger().warn('Key "%s" not found in the configuration', key) # 在需要的地方调用 update_config_value 函数来更新值 update_config_value('param_name', 'new_value') 4. 保存修改后的文件: ```python with open(self.config_file, 'w') as stream: yaml.safe_dump(self.config_data, stream, default_flow_style=False) ``` 记得在实际应用中处理异常,并确保有足够的权限来写入文件,特别是在运行受限的环境中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值