[ros2 launch] launch file argument to python variable
Suppose I pass an argument to a launch file by ros2 launch file.launch.py arg:='temp'
. I'd like to pass this into a variable in the launch file such that I can use it, e.g.
def generate_launch_description():
arg = DeclareLaunchArgument("arg", default_value="temp")
output = arg.value + ".yaml"
The expectation is that, given the ros2 launch
call from before, output
becomes "temp.yaml"
. In essence I am looking for how to do this arg.value
part, I can't find anything in this direction online. I have an idea that I need to use substitutions but the documentation on how it works seems to be relatively limited.
Asked by morten on 2021-09-30 05:31:24 UTC
Answers
You're looking for the LaunchConfiguration
Substitution:
...
from launch.substitution import LaunchConfiguration
def generate_launch_description():
arg = LaunchConfiguration('arg')
return LaunchDescription([
DeclareLaunchArgument("arg", default_value="temp"),
ExecuteProcess(cmd=['cat', (arg, '.yaml')])
])
Keep in mind that arg
is not a python string object. Ie type(arg) == str
is false. So you can't do normal string things with it. When I need to concatenate things to arg
, I'll usually put them into tuples such as (arg, '.yaml')
. When the substitution happens, this tuple gets concatenated together. The other thing to keep in mind, is that this arg
object can only really be used when the type-hints have a SomeSubstitutionsType
type. If you look at the ExecuteAction
class, you'll see that the cmd
argument should be of type Iterable[SomeSubstitutionsType]
. That's how you know if the substitution variable will be valid or not.
Hope that gives you enough direction to get you going.
Asked by ChuiV on 2021-10-07 20:56:31 UTC
Comments
Hi I have the same issue, did you find a solution without other to the
LaunchConfiguration
example provided by ChuiVAsked by Markus Bader on 2022-07-18 06:49:40 UTC