使用 Apache common-cli 解析参数 [英] Using Apache common-cli to parse arguments

查看:27
本文介绍了使用 Apache common-cli 解析参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apache common-cli 在其网站上有一个 ls 命令示例:

Apache common-cli has a example on its web site for ls command:

options.addOption( "a", "all", false, "do not hide entries starting with ." );
options.addOption( "A", "almost-all", false, "do not list implied . and .." );
options.addOption( "b", "escape", false, "print octal escapes for nongraphic " + "characters" );
options.addOption( OptionBuilder.withLongOpt( "block-size" )
                                .withDescription( "use SIZE-byte blocks" )
                                .hasArg()
                                .withArgName("SIZE")
                                .create() );

这会显示如下帮助:

-a, --all                  do not hide entries starting with .
-A, --almost-all           do not list implied . and ..
-b, --escape               print octal escapes for nongraphic characters
    --block-size=SIZE      use SIZE-byte blocks

  1. 当我编写这段代码时,它显示 --block-size .我想展示这样的东西:-z,--block-size=SIZE(不仅仅是长选项).
  2. PosixParserGnuParser 的区别是什么?我变了它们在代码中,我没有观察到任何区别.
  3. 当我提供错误的选项时,例如 h 它不会 throw 任何 ParseException.程序正常启动和结束.
  1. When I write this code, it shows --block-size <SIZE>. I want to show something like this: -z,--block-size=SIZE(not just long option).
  2. what is the difference of PosixParser and GnuParser? I changed them in the code, I didn't observed any difference.
  3. When I provide wrong option for example h it doesn't throw any ParseException. The program starts and finishes normally.

推荐答案

  1. 示例中的块大小选项只有长格式,这就是为什么没有显示短选项的原因.如果你添加一个短别名,你会得到你期望的结果

  1. The block size option in the example has only a long format, that's why there is no short option shown. If you add a short alias you'll get the result you expect

PosixParserGnuParser 在最新版本的 Commons CLI 中已弃用.一个新的统一解析器可用作 DefaultParser.posix 解析器能够解析连接的短选项,例如 tar -zxvf foo.tar.gz.

PosixParser and GnuParser are deprecated in the latest version of Commons CLI. A new unified parser is available as DefaultParser. The posix parser had the ability to parse concatenated short options, something like tar -zxvf foo.tar.gz.

额外选项要么作为应用程序的参数处理,要么触发异常,具体取决于 stopAtNonOption 解析器参数的值.

Extra options are either handled as arguments to the application or trigger an exception, depending of the value of the stopAtNonOption parser parameter.

这篇关于使用 Apache common-cli 解析参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆