get filename and path of `source`d file

前端 未结 6 1759
心在旅途
心在旅途 2020-12-08 08:20

How can a sourced or Sweaved file find out its own path?

Background:

I work a lot with .R scripts or .Rnw files. My projects are o

6条回答
  •  暖寄归人
    2020-12-08 09:02

    You can use sys.calls() to get the command used to source the file. Then you need a bit of trickery using regular expressions to get the pathname, bearing in mind that source("something/filename") could have used either the absolute or relative path. Here's a first attempt at putting all the pieces together: try inserting the following lines at the top of a source file.

    whereFrom=sys.calls()[[1]]
    # This should be an expression that looks something like
    # source("pathname/myfilename.R")
    whereFrom=as.character(whereFrom[2]) # get the pathname/filename
    whereFrom=paste(getwd(),whereFrom,sep="/") # prefix it with the current working directory
    pathnameIndex=gregexpr(".*/",whereFrom) # we want the string up to the final '/'
    pathnameLength=attr(pathnameIndex[[1]],"match.length")
    whereFrom=substr(whereFrom,1,pathnameLength-1)
    print(whereFrom) # or "setwd(whereFrom)" to set the working directory
    

    It's not very robust—for instance, it will fail on windows with source("pathname\\filename"), and I haven't tested what happens if you have one file sourcing another file—but you might be able to build a solution on top of this.

提交回复
热议问题