Linux 跳过未知的命令行参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3677135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:17:47  来源:igfitidea点击:

Skip unknown command line arguments

javacommand-linecommand-line-arguments

提问by Mamut

In a current application I have, the incoming command line parameters are parsed on several "levels".

在我当前的应用程序中,传入的命令行参数在几个“级别”上进行解析。

At the 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.

在最高级别,我只想解析一些选项,而将其余选项留给“较低级别”。但是,到目前为止,我尝试过的所有库(Common Cli、args4j、JOpt、gnu.jargs)都会在我尝试提供它们时抛出“未知选项”异常,好吧,未知选项。

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

谢谢

回答by os111

jopt lets you specify a default value. No exception is thrown.

jopt 允许您指定默认值。不会抛出任何异常。

parser.accepts("count").withOptionalArg().ofType(Integer.class).defaultsTo(-1);

回答by dnocode

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);

回答by takacsot

In case of Args4j I think the SubCommandHandlercould be just good enough. https://args4j.kohsuke.org/apidocs/org/kohsuke/args4j/spi/SubCommandHandler.html

在 Args4j 的情况下,我认为这SubCommandHandler可能就足够了。https://args4j.kohsuke.org/apidocs/org/kohsuke/args4j/spi/SubCommandHandler.html