8

我使用Apache Commons CLI来分析命令行参数。Apache Commons CLI中-help选项的多个参数值名称

我正在寻找一种方法来显示帮助中的多个参数值名称。 下面是选项 “startimport” 的一个参数的例子:

Option startimport = OptionBuilder 
       .withArgName("environment") 
       .hasArg() 
       .withDescription(
         "Description") 
       .create("startimport"); 

当我使用-help它打印出:

-startimport <environment>     Description 

Thatfs罚款。但是如果我想用两个参数呢?

Option startimport = OptionBuilder 
       .withArgName("firstArg secondArg") 
       .hasArgs(2) 
       .withDescription("Description") 
       .create("startimport "); 

解析两个参数是没有问题的,但我想在 “-help” 以下的输出:

startimport <firstArg> <secondArg>     Description 

但是目前,我只想得到:

startimport <firstArg secondArg>     Description 

是有那个问题的适当的解决方案?

回答

9

我用顽皮的方式来解决这个问题。

OptionBuilder.hasArgs(3); 
    OptionBuilder.withArgName("hostname> <community> <oid"); 
    OptionBuilder.withDescription("spans switch topology. Mutually exclusive with -s"); 
    Option my_a = OptionBuilder.create("a"); 

它现在在帮助中正确显示。虽然我不确定这是否有后果。

24

我找到了一种解决这个问题的方式,表现正确,并认为我会分享,因为这是Google在研究过程中让我带领的一页。此代码是使用Commons CLI 1.2编写的。

Option searchApp = OptionBuilder.withArgName("property> <value") 
      .withValueSeparator(' ') 
      .hasArgs(2) 
      .withLongOpt("test") 
      .withDescription("This is a test description.") 
      .create("t"); 

显示的帮助信息是这样的:

java -jar program.jar -t id 5 

和一个String []可以在检索到的参数:

-t,--test <property> <value> This is a test description. 

它可以从这样的命令行中使用代码如下:

Options options = new Options(); 
options.addOption(searchApp); 
PosixParser parser = new PosixParser(); 
CommandLine cmd = parser.parse(options, args); 
String[] searchArgs = cmd.getOptionValues("t"); 

然后,您可以使用searchArgs[0]searchArgs[1]检索值。

相关问题