我正在使用 argparse4j解析命令行参数。我想添加一个参数,当存在时,将 boolean 值设置为 true,否则默认为 false。我不想在参数中包含 true 或 false,只包含标识符,因此运行时它看起来像这样:
java firstArg --enable-boolean
This answer显示在 Python 中,我可以设置参数的 action
来存储 true 或 false 值,如下所示:
parser.add_argument('-b', action='store_true', default=False)
如何使用 argparse4j 在 Java 中做同样的事情?
最佳答案
您正在寻找 Arguments.storeTrue()
Action :
Arguments.storeTrue()
andArguments.storeFalse()
are special cases of Arguments.storeConst() using for storing valuestrue
andfalse
respectively. In addition, they create default values offalse
andtrue
respectively. For example:public static void main(String[] args) throws ArgumentParserException { ArgumentParser parser = ArgumentParsers.newArgumentParser("prog"); parser.addArgument("--foo").action(Arguments.storeTrue()); parser.addArgument("--bar").action(Arguments.storeFalse()); parser.addArgument("--baz").action(Arguments.storeFalse()); System.out.println(parser.parseArgs(args)); }
$ java Demo --foo --bar Namespace(baz=true, foo=true, bar=false)
关于java - 使用 Argparse4j 的命令行参数设置标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813481/