ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

If you're doing rosrun, you can use the argv passed into the main function of your C++ node:

int main(int argc, char** argv)
{
    // Note: this processes out some ROS specific things, what's left over is standard argv stuff
    ros::init(argc, argv, "my_node");

    if (argc > 1)
        std::string value_from_cl = argv[1];
}

If you go through a launch file, you can use launch file args to pass in from the command line. For example, if you have in your launch file

<arg name="some_arg" default="my_default_value"/>

then you can run roslaunch like

roslaunch my_package my_file.launch some_arg:=some_other_value

Then to get the value to your node, you can pass it directly in the node tag in the launch file:

<node name="my_node" pkg="my_package" type="my_node" args="$(arg some_arg)"/>

You could alternatively set it with the ROS parameter server, in which case you would load it in your launch file by doing

<param name="my_param" value="$(arg some_arg)"/>

which can then be retrieved from the parameter server in your C++ code with

ros::NodeHande nh;
std::string value_from_ps;
// Retrieve and set a default value if not found on parameter server    
nh.param<std::string>("my_param", value_from_ps, "my_default_value");
// Retrieve without a default value
nh.getParam("my_param", value_from_ps);

If you're doing rosrun, you can use the argv passed into the main function of your C++ node:

int main(int argc, char** argv)
{
    // Note: this processes out some ROS specific things, what's left over is standard argv stuff
    ros::init(argc, argv, "my_node");

    if (argc > 1)
        std::string value_from_cl = argv[1];
}

If you go through a launch file, you can use launch file args to pass in from the command line. For example, if you have in your launch file

<arg name="some_arg" default="my_default_value"/>

then you can run roslaunch like

roslaunch my_package my_file.launch some_arg:=some_other_value

Then to get the value to your node, you can pass it directly in the node tag in the launch file:

<node name="my_node" pkg="my_package" type="my_node" args="$(arg some_arg)"/>

You could alternatively set it with the ROS parameter server, in which case you would load it in your launch file by doing

<param name="my_param" value="$(arg some_arg)"/>

which can then be retrieved from the parameter server in your C++ code with

ros::NodeHande nh;
std::string value_from_ps;
// Retrieve and set a default value if not found on parameter server    
nh.param<std::string>("my_param", value_from_ps, "my_default_value");
// Retrieve without a default value
nh.getParam("my_param", value_from_ps);