Determine path of the executing script

前端 未结 28 2486
再見小時候
再見小時候 2020-11-22 08:01

I have a script called foo.R that includes another script other.R, which is in the same directory:

#!/usr/bin/env Rscript
message(\         


        
相关标签:
28条回答
  • 2020-11-22 08:43

    I like this approach:

    this.file <- sys.frame(tail(grep('source',sys.calls()),n=1))$ofile
    this.dir <- dirname(this.file)
    
    0 讨论(0)
  • 2020-11-22 08:44

    I couldn't get Suppressingfire's solution to work when 'source'ing from the R console.
    I couldn't get hadley's solution to work when using Rscript.

    Best of both worlds?

    thisFile <- function() {
            cmdArgs <- commandArgs(trailingOnly = FALSE)
            needle <- "--file="
            match <- grep(needle, cmdArgs)
            if (length(match) > 0) {
                    # Rscript
                    return(normalizePath(sub(needle, "", cmdArgs[match])))
            } else {
                    # 'source'd via R console
                    return(normalizePath(sys.frames()[[1]]$ofile))
            }
    }
    
    0 讨论(0)
  • 2020-11-22 08:44

    Amazing there is no '$0' type structure in R! You can do it with a system() call to a bash script written in R:

    write.table(c("readlink -e $0"), file="scriptpath.sh",col=F, row=F, quote=F)
    thisscript <- system("sh scriptpath.sh", intern = TRUE)
    

    Then just split out the scriptpath.sh name for other.R

    splitstr <- rev(strsplit(thisscript, "\\/")[[1]])
    otherscript <- paste0(paste(rev(splitstr[2:length(splitstr)]),collapse="/"),"/other.R")
    
    0 讨论(0)
  • 2020-11-22 08:45
    frame_files <- lapply(sys.frames(), function(x) x$ofile)
    frame_files <- Filter(Negate(is.null), frame_files)
    PATH <- dirname(frame_files[[length(frame_files)]])
    

    Don't ask me how it works though, because I've forgotten :/

    0 讨论(0)
提交回复
热议问题