# Python launch 中无法获取 LaunchArgument 值

> 原文链接：https://robotics.hellobike.com/pitfalls/2024-08-16-robotics-se-104340
> 频道：pitfalls | 更新日期：2024-08-16 | 标签：auto, stackexchange, ros2, python, launch-file, ros2-launch
> 核心摘要：在 ROS Python launch 中通过 OpaqueFunction 获取运行时 context，再调用 LaunchConfiguration.perform(context)…

# Python launch 中无法获取 LaunchArgument 值

::: v-pre
> 本文由 AI 根据公开内容整理，可能有误，请以原文为准：[Getting the value of LaunchArgument inside python Launch file](https://robotics.stackexchange.com/questions/104340/getting-the-value-of-launchargument-inside-python-launch-file)（Robotics Stack Exchange #104340）

**状态**：已解决

## 问题

提问者想在 Python launch 文件内部获取 `DeclareLaunchArgument` 的运行时值，但 `LaunchArgument` 变量本身无法直接取值，`LaunchConfiguration.perform(LaunchContext)` 又需要运行时 `LaunchContext`。

## 环境

ROS 2

## 解决办法

1. 定义 `OpaqueFunction(function=launch_setup)`，让 `launch_setup(context)` 接收正确的运行时 `context`。
2. 在 `launch_setup` 中使用 `LaunchConfiguration('config').perform(context)` 获取运行时参数值。
3. 根据该值执行后续逻辑，并返回要启动的 `Node` 等 action。
4. 在 `generate_launch_description()` 中创建 `LaunchDescription(launch_args)`，再用 `ld.add_action(opfunc)` 加入 `OpaqueFunction`。

原问题作者：Stanislav Svědiroh；采纳答案作者：Stanislav Svědiroh。原内容依 CC BY-SA 4.0 授权，本页摘要同样依 CC BY-SA 4.0 授权。
:::

## 原始参考来源 (Sources)

- [Robotics Stack Exchange #104340：Getting the value of LaunchArgument inside python Launch file](https://robotics.stackexchange.com/questions/104340/getting-the-value-of-launchargument-inside-python-launch-file)