副标题#e#
如果你曾经写过命令行程序,你可能会知道,一般来说,你所选择的语言有一个叫做 optparse 的库或模块。它是提供给程序员的,所以作为命令的一部分输入的选项(比如 -v 或 --verbose)可以与命令的其他部分进行解析。这可以帮助你的代码从一个子命令或参数中获取一个选项。
当为 FinSH 编写一个命令时,optparse 包希望使用这种格式:
MSH_CMD_EXPORT_ALIAS(pkgs, pkgs,thisistest cmd.);
你可以使用长形式或短形式,或者同时使用两种形式来实现选项。例如:
staticstruct optparse_long long_opts[]=
{
{"help" ,'h', OPTPARSE_NONE},// Long command: help, corresponding to short command h, without arguments.
{"force-update", 0, OPTPARSE_NONE},// Long comman: force-update, without arguments
{"update" , 0, OPTPARSE_NONE},
{"list" , 0, OPTPARSE_NONE},
{"wizard" , 0, OPTPARSE_NONE},
{"upgrade" , 0, OPTPARSE_NONE},
{"printenv" , 0, OPTPARSE_NONE},
{ NULL , 0, OPTPARSE_NONE}
};
创建完选项后,写出每个选项及其参数的命令和说明:
staticvoid usage(void)
{
rt_kprintf("usage: env.py package [-h] [--force-update] [--update] [--list] [--wizard]\n");
rt_kprintf(" [--upgrade] [--printenv]\n\n");
rt_kprintf("optional arguments:\n");
rt_kprintf(" -h, --help show this help message and exit\n");
rt_kprintf(" --force-update force update and clean packages, install or remove the\n");
rt_kprintf(" packages by your settings in menuconfig\n");
rt_kprintf(" --update update packages, install or remove the packages by your\n");
rt_kprintf(" settings in menuconfig\n");
rt_kprintf(" --list list target packages\n");
rt_kprintf(" --wizard create a new package with wizard\n");
rt_kprintf(" --upgrade upgrade local packages list and ENV scripts from git repo\n");
rt_kprintf(" --printenv print environmental variables to check\n");
}
下一步是解析。虽然你还没有实现它的功能,但解析后的代码框架是一样的:
int pkgs(int argc,char**argv)
{
int ch;
int option_index;
struct optparse options;
if(argc ==1)
{
usage();
return RT_EOK;
}
optparse_init(&options, argv);
#p#副标题#e#
while((ch = optparse_long(&options, long_opts,&option_index))!=-1)
{
ch = ch;
rt_kprintf("\n");
rt_kprintf("optopt = %c\n", options.optopt);
rt_kprintf("optarg = %s\n", options.optarg);
rt_kprintf("optind = %d\n", options.optind);
rt_kprintf("option_index = %d\n", option_index);
}
rt_kprintf("\n");
return RT_EOK;
}
这里是函数头文件:
#include"optparse.h"
#include"finsh.h"
然后,编译并下载到设备上。