ฉันเพิ่งรวบรวมโครงสร้างข้อมูลที่ดีและห่วงโซ่การประมวลผลเพื่อสร้างพฤติกรรมการสลับนี้โดยไม่จำเป็นต้องใช้ไลบรารี ฉันแน่ใจว่ามันจะถูกนำไปใช้หลายครั้งแล้ว และเจอกระทู้นี้เพื่อค้นหาตัวอย่าง - คิดว่าฉันจะเข้าไปช่วย
ฉันไม่ต้องการแฟล็กเป็นพิเศษด้วยซ้ำ (แฟล็กเดียวที่นี่คือโหมดดีบั๊ก โดยสร้างตัวแปรที่ฉันตรวจสอบเป็นเงื่อนไขในการเริ่มต้นฟังก์ชันดาวน์สตรีม 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 Print variables rather than executing function XYZ...
-h --help Display flag definitions
person
Louis Maddox
schedule
13.02.2015