一、通过main函数
参数保存在main函数的argc和argv变量中
int main(int argc, char** argv)
{
ros::init(argc, argv, "param_test");
if(argc > 1)
{
for(int i=1; i<argc; i++)
{
std::cout<<"argv["<<i<<"] "<<argv[i]<<std::endl;
}
}
return 0;
}
1)rosrun启动
rosrun param_test param_test arg1 arg2
输出结果:
argv[1] arg1
argv[2] arg2
2)也可以找到可执行程序 param_test 所在的目录,直接在目录下运行
./param_test arg1 arg2
输出结果同 1)
3)roslaunch启动,要用到结点的args属性
新建lanuch文件
<launch>
<node pkg="param_test" type="param_test" name="param_test" args="arg1 arg2" output="screen"/>
</launch>
启动launch
roslaunch param_test param_test.launch
输出结果同 1)
缺点是如果参数变化,每次都要修改launch文件。
4)还有一种方式是3)方法的改进,使用arg元素在命令行动态传参
<launch>
<arg name="my_args" default="arg1 arg2"/>
<node pkg="param_test" type="param_test" name="param_test" args="$(arg my_args)" output="screen"/>
</launch>
my_args的默认参数是"arg1 arg2",启动launch,给my_args赋值arg3 arg4
roslaunch param_test param_test.launch my_args:="arg3 arg4"
输出结果:
argv[1] arg3
argv[2] arg4
二、通过参数服务器
int main(int argc, char** argv)
{
ros::init(argc, argv, "param_test");
//全局命名空间
ros::NodeHandle n;
std::string n_arg;
n.param<std::string>("n_arg",n_arg,"default_arg1");
std::cout<<"n_arg="<<n_arg<<std::endl;
//私有命名空间
std::string pn_arg;
ros::NodeHandle pn("~");
pn.param<std::string>("pn_arg",pn_arg,"default_arg2");
std::cout<<"pn_arg="<<pn_arg<<std::endl;
return 0;
}
1)roslaunch+arg
新建launch文件
<launch>
<arg name="arg1" default="this is arg1" />
<arg name="arg2" default="this is arg2" />
<param name="n_arg" value="$(arg arg1)" />
<node pkg="param_test" type="param_test" name="param_test" output="screen">
<param name="pn_arg" value="$(arg arg2)"/>
</node>
</launch>
参数n_arg在全局命名空间中访问,而pn_arg在节点的私有命名空间 “~” 中访问。和上文一样,arg1、arg2可以在roslaunch的时候通过命令行指定,如果不在命令行指定,使用的是launch文件设定的默认值。
roslaunch param_test param_test.launch arg2:=wooow
输出结果:
n_arg=this is arg1
pn_arg=wooow
2)rosrun启动,并指定私有参数~parameter,注意“~”用下划线代替。
rosrun param_test param_test _pn_arg:=hahahaha
输出结果:
n_arg=default_arg1
pn_arg=hahahaha
链接:
https://blog.csdn.net/u013834525/article/details/88744327
https://answers.ros.org/question/277622/roslaunch-command-line-args/
网友评论