Determine path of the executing script

前端 未结 28 2540
再見小時候
再見小時候 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: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))
            }
    }
    

提交回复
热议问题