ROS2 python-launchfile: Load parameters.yaml into node's parameter

asked 2022-02-24 05:27:27 -0500

fexner gravatar image

Imagine, I have a file parameters.yaml:

answer_to_everything: 42
pi: 3.14

Then, there's a node that expects a dictionary parameter numbers. I would like the dictionary generated from parameters.yaml to be passed to the node into the parameter numbers.

Without the file that could be achieved with

my_node = Node(
    package="example_package",
    executable="example_node",
    parameters=[{
        "numbers": {
            "answer_to_everything": 42,
            "pi": 3.14
            }}],
)

Is it possible to easily achieve something like this? The only working solution I could come up with involves loading the file using the yaml module an setting the dictionary directly:

numbers_file = os.path.join(
    get_package_share_directory("my_package"), "config", "parameters.yaml"
)
with open(numbers_file, "r") as stream:
    try:
        numbers = yaml.safe_load(stream)
    except yaml.YAMLError as exc:
        print(exc)
my_node = Node(
    package="example_package",
    executable="example_node",
    parameters=[{"numbers": numbers}],
)

First of all that solution feels ugly and second I'd like to make the actual parameter file a launch file argument. However, os.path.join will need a string and no LaunchConfiguration object. As far as I understand, LaunchConfiguration are not supposed to be converted to strings inside the launch file.

Oh, and as a closing remark: I'd like to use this structure, as the parameters.yaml file is already used in another place (and shall not be duplicated), so I can't convert it to a syntax that can be directly passed to the node, as I don't want to / can't have the namespace/ros__parameters levels in there.

edit retag flag offensive close merge delete