【问题标题】:Commons CLI required groupsCommons CLI 所需的组
【发布时间】:2020-04-06 18:49:59
【问题描述】:

我正在用 Java 编写命令行应用程序,并且我选择了 Apache Commons CLI 来解析输入参数。

假设我有 两个必需选项(即 -input 和 -output)。我创建新的 Option 对象并设置所需的标志。现在一切都很好。但我有第三个,不是必需的选项,即。 -帮助。使用我提到的设置,当用户想要显示帮助(使用 -help 选项)时,它会说“-input and -output”是必需的。有没有办法实现这个(通过 Commons CLI API,不简单 if (!hasOption) throw new XXXException())。

【问题讨论】:

    标签: java command-line-interface apache-commons apache-commons-cli


    【解决方案1】:

    在这种情况下,您必须定义两组选项并解析命令行两次。第一组选项包含所需组之前的选项(通常是 --help--version),第二组包含所有选项。

    首先解析第一组选项,如果没有找到匹配项,则继续第二组。

    这是一个例子:

    Options options1 = new Options();
    options1.add(OptionsBuilder.withLongOpt("help").create("h"));
    options1.add(OptionsBuilder.withLongOpt("version").create());
    
    // this parses the command line but doesn't throw an exception on unknown options
    CommandLine cl = new DefaultParser().parse(options1, args, true);
    
    if (!cl.getOptions().isEmpty()) {
    
        // print the help or the version there.
    
    } else {
        OptionGroup group = new OptionGroup();
        group.add(OptionsBuilder.withLongOpt("input").hasArg().create("i"));
        group.add(OptionsBuilder.withLongOpt("output").hasArg().create("o"));
        group.setRequired(true);
    
        Options options2 = new Options();
        options2.addOptionGroup(group);
    
        // add more options there.
    
        try {
            cl = new DefaultParser().parse(options2, args);
    
            // do something useful here.
    
        } catch (ParseException e) {
            // print a meaningful error message here.
        }
    }
    

    【讨论】:

    • 好的。但是我怎么能说我没有找到匹配项呢? (“如果没有找到匹配项”)?如果我设置了 required 标志,我会得到 ParseExeception,但是当我通过不可用的选项时,我也会得到 ParseException :( 如何区分这种情况?
    • commandline.getOptions() 不为空时,您知道是否匹配到了。
    • 这或多或少是我在想的。我试图避免双重捕获(对于第一次和第二次解析) - 认为它看起来很糟糕。但我认为没有办法做到这一点。在我看来,Commons Cli 实现应该允许创建组(互斥),然后将组添加到另一个组。所以简单地 group(help, group(in, out)) 就可以了。例如,谢谢。保重!
    • 重要的是要注意,现在 OptionsBuilder 已被弃用,应该使用 options.builder。
    • @Karl-AnderoMere 对于格式化程序,您使用 OptionGroup 和所有选项
    【解决方案2】:

    commons-cli 库有一个流利的包装器:https://github.com/bogdanovmn/java-cmdline-app

    帮助选项是内置的。还有一些方便的功能。 例如,如果您必须指定以下两个选项之一:

    new CmdLineAppBuilder(args)
    // Optional argument
    .withArg("input", "input description")
    .withArg("output", "output description")
    
    // "input" or "output" must be specified
    .withAtLeastOneRequiredOption("input", "output")
    
    .withEntryPoint(
        cmdLine -> {
            ...
        }
    ).build().run();
    

    【讨论】:

      猜你喜欢
      • 2013-03-21
      • 2012-07-19
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 2018-01-21
      • 2014-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多