Skip unknown command line arguments
In a current application I have, the incoming command line parameters are parsed on several "levels".
At 开发者_如何学Pythonthe highest level I only wish to parse some options and leave the rest to "lower levels". however, all libraries I've tried so far (Common Cli, args4j, JOpt, gnu.jargs) al throw an "unknown option" exception when I'm trying to feed them, well, unknown options.
I really don't want to write a yet another command line parsing class. Is there a library/class that parses these options and skips over unknown options?
Thank you
There is a better solution.
public static BiFunction<String[],CmdLineParser,String[]> stripUnusedArgs=(args,parser)->{
List<String> accepteds=parser.getOptions().stream().map(opt->opt.option.toString()).collect(Collectors.toList());
List<String> stripedArgs=new ArrayList<>();
for(int i=0; i< args.length;i++){
if(accepteds.contains(args[i])){
stripedArgs.add(args[i]);
stripedArgs.add(args[i+1]);
}
}
return stripedArgs.toArray(new String[0]);
};
And then to use it:
CmdLineParser parser = new CmdLineParser(CustomArgsObject);
stripUnusedArgs.apply(args,parser);
jopt lets you specify a default value. No exception is thrown.
parser.accepts("count").withOptionalArg().ofType(Integer.class).defaultsTo(-1);
In case of Args4j I think the SubCommandHandler
could be just good enough. https://args4j.kohsuke.org/apidocs/org/kohsuke/args4j/spi/SubCommandHandler.html
精彩评论