You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将非字典Python对象转储为YAML?解决ROS2域桥重复键配置问题

生成含重复键的ROS2 Domain Bridge YAML配置

Python标准字典不允许重复键,直接用yaml.dump()处理普通字典会丢失重复的simulation/odometry条目,下面提供两种可行方案:

方案1:使用ruamel.yaml(推荐)

ruamel.yaml是PyYAML的增强实现,原生支持重复键的解析与生成,操作更简洁:

  1. 安装依赖:
pip install ruamel.yaml
  1. 编写生成脚本:
from ruamel.yaml import YAML

# 初始化YAML处理器并允许重复键
yaml = YAML()
yaml.allow_duplicate_keys = True

# 构建配置结构(topics用键值对列表存储,支持重复键)
bridge_config = {
    "name": "ol_bridge",
    "topics": [
        (
            "simulation/odometry",
            {
                "type": "nav_msgs/msg/Odometry",
                "from_domain": 88,
                "to_domain": 40,
                "remap": "simulation/odom_88"
            }
        ),
        (
            "simulation/odometry",
            {
                "type": "nav_msgs/msg/Odometry",
                "from_domain": 89,
                "to_domain": 40,
                "remap": "simulation/odom_89"
            }
        )
    ]
}

# 写入配置文件
with open("domain_bridge.yaml", "w") as f:
    yaml.dump(bridge_config, f)

执行后即可生成符合要求的YAML文件,自动保留重复的simulation/odometry键。

方案2:原生PyYAML自定义节点构建

如果不想引入第三方库,可以直接操作PyYAML的节点API,手动构建包含重复键的映射结构:

import yaml
from yaml.nodes import MappingNode, ScalarNode

# 自定义表示器:将键值对列表转成带重复键的YAML映射
def represent_duplicate_map(dumper, data):
    mapping_node = MappingNode(tag="tag:yaml.org,2002:map", value=[])
    for key, val in data:
        key_node = ScalarNode(tag="tag:yaml.org,2002:str", value=key)
        val_node = dumper.represent_data(val)
        mapping_node.value.append((key_node, val_node))
    return mapping_node

# 注册表示器,让PyYAML用自定义逻辑处理键值对列表
yaml.add_representer(list, represent_duplicate_map)

# 构建配置
bridge_config = {
    "name": "ol_bridge",
    "topics": [
        (
            "simulation/odometry",
            {
                "type": "nav_msgs/msg/Odometry",
                "from_domain": 88,
                "to_domain": 40,
                "remap": "simulation/odom_88"
            }
        ),
        (
            "simulation/odometry",
            {
                "type": "nav_msgs/msg/Odometry",
                "from_domain": 89,
                "to_domain": 40,
                "remap": "simulation/odom_89"
            }
        )
    ]
}

# 生成YAML文件
with open("domain_bridge.yaml", "w") as f:
    yaml.dump(bridge_config, f, default_flow_style=False)

这种方式通过绕过Python字典的限制,直接构建YAML抽象语法树节点,实现重复键的输出。

内容的提问来源于stack exchange,提问作者user17579347

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 12:17:44