Determine path of the executing script

前端 未结 28 2487
再見小時候
再見小時候 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:25

    Note that the getopt package provides the get_Rscript_filename function, which just uses the same solution presented here, but is already written for you in a standard R module, so you don't have to copy and paste the "get script path" function into every script you write.

    0 讨论(0)
  • 2020-11-22 08:25

    See findSourceTraceback() of the R.utils package, which

    Finds all 'srcfile' objects generated by source() in all call frames. This makes it possible to find out which files are currently scripted by source().

    0 讨论(0)
  • 2020-11-22 08:26

    The answer of rakensi from Getting path of an R script is the most correct and really brilliant IMHO. Yet, it's still a hack incorporating a dummy function. I'm quoting it here, in order to have it easier found by others.

    sourceDir <- getSrcDirectory(function(dummy) {dummy})

    This gives the directory of the file where the statement was placed (where the dummy function is defined). It can then be used to set the working direcory and use relative paths e.g.

    setwd(sourceDir)
    source("other.R")
    

    or to create absolute paths

     source(paste(sourceDir, "/other.R", sep=""))
    
    0 讨论(0)
  • 2020-11-22 08:27

    A slimmed down variant of Supressingfire's answer:

    source_local <- function(fname){
        argv <- commandArgs(trailingOnly = FALSE)
        base_dir <- dirname(substring(argv[grep("--file=", argv)], 8))
        source(paste(base_dir, fname, sep="/"))
    }
    
    0 讨论(0)
  • 2020-11-22 08:27
    #!/usr/bin/env Rscript
    print("Hello")
    
    # sad workaround but works :(
    programDir <- dirname(sys.frame(1)$ofile)
    source(paste(programDir,"other.R",sep='/'))
    source(paste(programDir,"other-than-other.R",sep='/'))
    
    0 讨论(0)
  • 2020-11-22 08:29

    Steamer25's approach works, but only if there is no whitespace in the path. On macOS at least the cmdArgs[match] returns something like /base/some~+~dir~+~with~+~whitespace/ for /base/some\ dir\ with\ whitespace/.

    I worked around this by replacing the "~+~" with a simple whitespace before returning it.

    thisFile <- function() {
      cmdArgs <- commandArgs(trailingOnly = FALSE)
      needle <- "--file="
      match <- grep(needle, cmdArgs)
      if (length(match) > 0) {
        # Rscript
        path <- cmdArgs[match]
        path <- gsub("\\~\\+\\~", " ", path)
        return(normalizePath(sub(needle, "", path)))
      } else {
        # 'source'd via R console
        return(normalizePath(sys.frames()[[1]]$ofile))
      }
    }
    

    Obviously you can still extend the else block like aprstar did.

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