我只是组合了一个很好的数据结构和处理链来生成这种切换行为,不需要库。我敢肯定它会被多次实现,并且遇到这个线程寻找示例 - 以为我会参与。
我什至没有特别需要标志(这里唯一的标志是调试模式,创建一个变量,我检查它作为启动下游函数if (!exists(debug.mode)) {...} else {print(variables)}) 的条件。下面的标志检查lapply 语句产生同:
if ("--debug" %in% args) debug.mode <- T
if ("-h" %in% args || "--help" %in% args)
其中args 是从命令行参数读取的变量(一个字符向量,例如,当您提供这些参数时,相当于c('--debug','--help'))
它可用于任何其他标志,避免所有重复,并且没有库,因此没有依赖关系:
args <- commandArgs(TRUE)
flag.details <- list(
"debug" = list(
def = "Print variables rather than executing function XYZ...",
flag = "--debug",
output = "debug.mode <- T"),
"help" = list(
def = "Display flag definitions",
flag = c("-h","--help"),
output = "cat(help.prompt)") )
flag.conditions <- lapply(flag.details, function(x) {
paste0(paste0('"',x$flag,'"'), sep = " %in% args", collapse = " || ")
})
flag.truth.table <- unlist(lapply(flag.conditions, function(x) {
if (eval(parse(text = x))) {
return(T)
} else return(F)
}))
help.prompts <- lapply(names(flag.truth.table), function(x){
# joins 2-space-separatated flags with a tab-space to the flag description
paste0(c(paste0(flag.details[x][[1]][['flag']], collapse=" "),
flag.details[x][[1]][['def']]), collapse="\t")
} )
help.prompt <- paste(c(unlist(help.prompts),''),collapse="\n\n")
# The following lines handle the flags, running the corresponding 'output' entry in flag.details for any supplied
flag.output <- unlist(lapply(names(flag.truth.table), function(x){
if (flag.truth.table[x]) return(flag.details[x][[1]][['output']])
}))
eval(parse(text = flag.output))
请注意,在flag.details 中,命令存储为字符串,然后使用eval(parse(text = '...')) 进行评估。 Optparse 显然适用于任何严肃的脚本,但有时功能最少的代码也很好。
样本输出:
$ Rscript check_mail.Rscript --help
--debug 打印变量而不是执行函数 XYZ...
-h --help 显示标志定义