代码语言:javascript复制
thisPath <- function() {
cmdArgs <- commandArgs(trailingOnly = FALSE) if (length(grep("^-f$", cmdArgs)) > 0) { # R console option
normalizePath(dirname(cmdArgs[grep("^-f", cmdArgs) 1]))[1]
} else if (length(grep("^--file=", cmdArgs)) > 0) { # Rscript/R console option
scriptPath <- normalizePath(dirname(sub("^--file=", "", cmdArgs[grep("^--file=", cmdArgs)])))[1]
} else if (Sys.getenv("RSTUDIO") == "1") { # RStudio
dirname(rstudioapi::getSourceEditorContext()$path)
} else if (is.null(attr(stub, "srcref")) == FALSE) { # 'source'd via R console
dirname(normalizePath(attr(attr(stub, "srcref"), "srcfile")$filename))
} else { stop("Cannot find file path")
}
}
getProgramName<-function(arguments){
args <- commandArgs(trailingOnly = FALSE)
sub("--file=", "", args[grep("--file=", args)])
}
program <- getProgramName()
Path <- thisPath()
cat(Path,"t",program,"n",file=stderr())
将以上代码保存到 getPathProgram.R,然后运行
代码语言:javascript复制Rscript getPathProgram.R
显示结果如下:
/bi/8.xuxiong/work getPath.R