简体   繁体   English

optparse-applicative:至少需要一个参数

[英]optparse-applicative: Require at least one argument

I'm using the optparse-applicative library in an application that takes multiple strings on the command line and performs an action on each one. 我在一个应用程序中使用optparse-applicative库,该库在命令行中使用多个字符串,并对每个字符串执行一个操作。 My first try was this: 我的第一次尝试是这样的:

arguments Just
    ( metavar "EXPR"
    & help "Expressions to render, in zero-based De Bruijn index notation" )

Unfortunately, this allows running the program with no arguments, even though it doesn't make much sense. 不幸的是,即使没有太大意义,这也允许不带参数地运行程序。

My second attempt involved parsing the first argument separately, then consing it to the remainder of the list: 我的第二次尝试包括分别解析第一个参数,然后将其限制在列表的其余部分:

(:) <$> argument Just ( metavar "EXPR" )
    <*> arguments Just ( metavar "EXPR" )

This should have worked, but it didn't: when called with --help , the parser gobbles it up and processes it instead of displaying the help text. 这本来应该起作用,但是没有起作用:当使用--help调用时,解析器吞噬并处理它,而不显示帮助文本。

So my question is: how do I configure optparse to require at least one argument? 所以我的问题是:如何配置optparse至少需要一个参数?

Okay – I've reported this issue to the author of the library (Paolo Capriotti). 好的–我已将此问题报告给图书馆的作者(Paolo Capriotti)。 He replied: 他回答:

The problem here is that arguments has some special logic to: 这里的问题是arguments具有某些特殊逻辑以:

  • initially ignore arguments starting with '-' 最初忽略以'-'开头的参数
  • accept '--' 接受'-'
  • accept arguments starting with '-' after '--' is encountered 在遇到'-'之后接受以'-'开头的参数

Given this desired behavior, arguments cannot simply be implemented as many argument . 鉴于这种期望的行为, arguments不能简单地实现为many argument

What we can do to make common use cases like the one in this Issue easier to deal with, is to add a bunch of convenience builders, like: 为了使像本期这样的常见用例更易于处理,我们可以做的是添加一堆便利构建器,例如:

  • arguments1 , non-empty argument list, with the same behavior as arguments arguments1 ,非空参数列表,具有与参数相同的行为
  • argument' , parse 1 argument, ignoring things starting with '-' argument' ,解析1个参数,忽略以'-'开头的内容

This way, many argument' would be similar to arguments (without the special handling of --), and some argument' to arguments1. 这样,许多参数将类似于参数(不对-进行特殊处理),而某些参数将类似于arguments1。

Suggestions for better names are welcome. 欢迎提出更好的名字的建议。 :) :)

In other words, he added a new function arguments1 to do what I described. 换句话说,他添加了一个新的arguments1来执行我描述的操作。 That function has been available since version 0.5. 该功能自版本0.5起可用。

So now my code looks like this: 所以现在我的代码看起来像这样:

arguments1 Just
    ( metavar "EXPR"
   <> help "Expressions to render, in zero-based De Bruijn index notation" )

Thanks, Paolo! 谢谢,保罗!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM