使用命令行参数时出现 R optparse 错误

8
由于某些原因,此脚本中的 optparse 用法出现错误: test.R:
#!/usr/bin/env Rscript
library("optparse")

option_list <- list(
    make_option(c("-n", "--name"), type="character", default=FALSE,
                dest="report_name", help="A different name to use for the file"),
    make_option(c("-h", "--height"), type="numeric", default=12,
                dest = "plot_height", help="Height for plot [default %default]",
                metavar="plot_height"),
    make_option(c("-w", "--width"), type="numeric", default=10,
                dest = "plot_width", help="Width for plot [default %default]",
                metavar="plot_width")
)

opt <- parse_args(OptionParser(option_list=option_list), positional_arguments = TRUE)
print(opt)

report_name <- opt$options$report_name
plot_height <- opt$options$plot_height
plot_width <- opt$options$plot_width

input_dir <- opt$args[1] # input directory

I get this error:

    $ ./test.R --name "report1" --height 42 --width 12 foo
Error in getopt(spec = spec, opt = args) :
  redundant short names for flags (column 2).
Calls: parse_args -> getopt
Execution halted

然而,如果我从这一行中删除"-h"

make_option(c("--height"), type="numeric", default=12,
                    dest = "plot_height", help="Height for plot [default %default]"

看起来它运行良好;

$ ./test.R --name "report1" --height 42 --width 12 foo
$options
$options$report_name
[1] "report1"

$options$plot_height
[1] 42

$options$plot_width
[1] 12

$options$help
[1] FALSE


$args
[1] "foo"

有什么想法可能是在这里发生了什么?
我正在使用 R 3.3.0 和 optparse_1.3.2 (getopt_1.20.0)。
1个回答

11

-h标志是被optparse保留的(optparse被描述为getopt没有的一个功能,来自Github上getopt.R源文件的说明):

optparse包中实现的一些功能在getopt中不可用:

2. 当遇到“-h”时,自动生成帮助选项并打印帮助文本

因此,当用户指定-h时,唯一性检查失败。然而,问题跟踪器似乎没有提到需要为这种情况创建更好的错误消息。

最后,注意optparse似乎调用了getopt,因为它们有相同的作者。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接