Determine path of the executing script

前端 未结 28 3229
再見小時候
再見小時候 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条回答
  •  猫巷女王i
    2020-11-22 08:36

    I liked steamer25's solution as it seems the most robust for my purposes. However, when debugging in RStudio (in windows), the path would not get set properly. The reason being that if a breakpoint is set in RStudio, sourcing the file uses an alternate "debug source" command which sets the script path a little differently. Here is the final version which I am currently using which accounts for this alternate behavior within RStudio when debugging:

    # @return full path to this script
    get_script_path <- function() {
        cmdArgs = commandArgs(trailingOnly = FALSE)
        needle = "--file="
        match = grep(needle, cmdArgs)
        if (length(match) > 0) {
            # Rscript
            return(normalizePath(sub(needle, "", cmdArgs[match])))
        } else {
            ls_vars = ls(sys.frames()[[1]])
            if ("fileName" %in% ls_vars) {
                # Source'd via RStudio
                return(normalizePath(sys.frames()[[1]]$fileName)) 
            } else {
                # Source'd via R console
                return(normalizePath(sys.frames()[[1]]$ofile))
            }
        }
    }
    

提交回复
热议问题