1 commandArgs
类似于Python的sys.argv
# test1.RcommandArgs()
1.1 从stdin读取脚本并运行,通过—args传入参数
1.2 通过Rscript运行脚本,直接传入参数
1.3 设置trailingOnly=TRUE, 只保留参数本身
# test1.RcommandArgs(trailingOnly=TRUE) # or commandArgs(T)


2 optparse包
类似Python的argparse模块
if (!requireNamespace('optparse', quietly = TRUE)) {install.packages('optparse')}option_list <- list(make_option(c('-i', '--infile'), dest='infile', default=NULL, help='The input file.'),make_option(c('-o', '--outfile'), dest='outfile', default=NULL, help='The output file.'),make_option(c('--height'), dest='height', type='integer', default=1000, help='The height of image[default=%default].'),make_option(c('--width'), dest='width', type='integer', default=1000, help='The width of image[default=%default].'),make_option(c('--main'), dest='main', default='', help='The main title of image[default="%default"].'))parser <- OptionParser(option_list=option_list,usage='Rscript $prog [options]',description='\tArguments parse test.',epilogue='\tcontact: suqingdong@novogene.com.')args <- parse_args(parser)infile <- args$infileoutfile <- args$outfileheight <- args$heightwidth <- args$widthmain <- args$main
PS:
- dest: opt$destname, 默认为较长的opt_str
- metavar: 打印帮助信息时,显示的参数名, 默认为dest的值
- type either “logical”, “integer”, “double”, “complex”, or “character”
- %prog, %default可用于变量的引用
另一种使用方式, 更像Python的argparse使用方式
parser <- OptionParser(usage='Rscript $prog [options]',description='\tArguments parse test.',epilogue='\tcontact: suqingdong@novogene.com.')parser <- add_option(parser, c('-i', '--infile'), action='store', default=NULL, help='The input file.')parser <- add_option(parser, c('-o', '--outfile'), action='store', default='out.png', help='The input file[default %default].')args <- parse_args(parser)print(args$i)print(args$o)
同时使用关键词参数和位置参数 positional_arguments = TRUE
if (!requireNamespace('optparse', quietly = TRUE)) {install.packages('optparse', repos='https://mirrors.tuna.tsinghua.edu.cn/CRAN/')}library(optparse)parser <- OptionParser(prog='test',usage='Rscript %prog [options]',description='\t\033[32m arguments parse test \033[0m',epilogue='contact: suqingdong@novogene.com.')add_option(parser, c('-i', '--infile'), action='store', default=NULL, help='The input file.')add_option(parser, c('-o', '--outfile'), action='store', default='out.png', help='The input file[default %default].')opt <- parse_args(parser, positional_arguments = TRUE)print(opt$i)print(opt$o)print(opt$args)
3 argparse包
suppressWarnings(library(argparse))parser = ArgumentParser(description='convert rds to table')parser$add_argument('-i', '--infile', help='the input rds file', required=T)parser$add_argument('-o', '--outfile', help='the output table file', required=T)args = parser$parse_args()
