【问题标题】:docopt - require specific data type for each argdocopt - 需要每个 arg 的特定数据类型
【发布时间】:2016-08-10 14:21:31
【问题描述】:

我通常在 Python 中使用 argparse,在 R 中使用 docopt。我在 argparse 中错过的一个我还没有在 docopt 中发现的功能是能够为每个参数指定所需的数据类型。例如,在 argparse 中,我需要一个整数输入,使用

parser.add_argument("square", help="display a square of a given number",
                type=int)

在 docopt / R 中,我在文档中找不到任何关于需要特定数据类型的内容。

-s <square>, --square=<square>   display a square of a given number #additional option to require integer input?

在 Python 版本的 docopt GitHub repo 上有一个封闭的issue,这似乎表明这不是基本 docopt 的一部分,并为 Python 提供了解决方案,但这并不直接适用于 R。任何人都可以提供在 R 中使用 docopt 验证参数输入的任何建议/更优雅的方法?

【问题讨论】:

    标签: python r docopt


    【解决方案1】:

    我有点好奇为什么你不在 python 中使用docopt,或者你为什么不在 R 中使用argparse(或optparse)?

    如果您想知道这是如何使用 optparse R 包完成您请求的功能:

    > library("optparse")
    > parser = OptionParser()
    > parser = add_option(parser, c("-s", "--square"), 
    +    type="integer", 
    +    help="display a square of a given number")
    > typeof(parse_args(parser, "--square=5")$square)
    [1] "integer"
    

    如何使用argparse 包(后者具有 python 依赖项)来做到这一点:

    > parser = argparse::ArgumentParser()
    > parser$add_argument("-s", "--square", 
    +    type="integer",
    +    help="display a square of a given number")
    > typeof(parser$parse_args("--square=5")$square)
    [1] "integer"
    

    【讨论】:

      【解决方案2】:

      不确定这是否足够优雅,因为它涉及设置默认值,然后使用utils::type.convert 确定类/类型

      "Usage: my_program.R [-hson FILE] [--quiet | --verbose] [INPUT ...]
      
      -h --help        show this 
      -s --sorted      sorted output
      --coefficient=K  [default: 2.95] The K coefficient 
      --numSim=K       [default: 200] number of simulations 
      --output=FILE    [default: test.txt] Output file 
      --directory=DIR  [default: ./] Some directory 
      -o FILE          specify output file [default: ./test.txt]
      --quiet          print less text
      --verbose        print more text" -> doc
      opts <- docopt(doc, "-s --quiet")
      str(opts)
      
      newopts <- lapply(opts, function(x) utils::type.convert(as.character(x),as.is=T))
      (definedClasses <- unlist(lapply(newopts, typeof)))
      

      当您运行程序时,您可以针对此definedClasses 测试输入。

      您可能还想查看 getoptoptparse/argparse 软件包以及此 SO 帖子 Parsing command line arguments in R scripts

      参考资料:

      http://docopt.org

      http://rgrannell1.github.io/blog/2014/08/04/command-line-interfaces-in-r

      http://docopt.readthedocs.org/en/0.2.0/

      【讨论】:

      • 谢谢,这是有趣的信息。将来我可能会尝试这种方法。我最终使用 testthat 包编写测试来检查用户输入是否符合预期。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 2016-01-12
      相关资源
      最近更新 更多