Determine path of the executing script

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

提交回复
热议问题