Determine path of the executing script

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

    I would use a variant of @steamer25 's approach. The point is that I prefer to obtain the last sourced script even when my session was started through Rscript. The following snippet, when included on a file, will provided a variable thisScript containing the normalized path of the script. I confess the (ab)use of source'ing, so sometimes I invoke Rscript and the script provided in the --file argument sources another script that sources another one... Someday I will invest in making my messy code turns into a package.

    thisScript <- (function() {
      lastScriptSourced <- tail(unlist(lapply(sys.frames(), function(env) env$ofile)), 1)
    
      if (is.null(lastScriptSourced)) {
        # No script sourced, checking invocation through Rscript
        cmdArgs <- commandArgs(trailingOnly = FALSE)
        needle <- "--file="
        match <- grep(needle, cmdArgs)
        if (length(match) > 0) {
          return(normalizePath(sub(needle, "", cmdArgs[match]), winslash=.Platform$file.sep, mustWork=TRUE))
        }
      } else {
        # 'source'd via R console
        return(normalizePath(lastScriptSourced, winslash=.Platform$file.sep, mustWork=TRUE))
      }
    })()
    

提交回复
热议问题