获取当前脚本的路径

时间:2022-10-14 23:42:53

I would like to set the working directory to the path of current script programmatically but first I need to get the path of current script.

我想以编程方式将工作目录设置为当前脚本的路径,但首先我需要获取当前脚本的路径。

So I would like to be able to do:

所以我希望能够做到:

current_path = ...retrieve the path of current script ...
setwd(current_path) 

Just like the RStudio menu does: 获取当前脚本的路径

就像RStudio菜单一样:

So far I tried:

到目前为止我尝试过:

initial.options <- commandArgs(trailingOnly = FALSE)
file.arg.name <- "--file="
script.name <- sub(file.arg.name, "", initial.options[grep(file.arg.name, initial.options)])
script.basename <- dirname(script.name)

script.name returns NULL

script.name返回NULL

source("script.R", chdir = TRUE)

Returns: Error in file(filename, "r", encoding = encoding) : cannot open the connection In addition: Warning message: In file(filename, "r", encoding = encoding) : cannot open file '/script.R': No such file or directory

返回:文件中的错误(文件名,“r”,编码=编码):无法打开连接另外:警告消息:在文件中(文件名,“r”,编码=编码):无法打开文件'/script.R' : 无此文件或目录

dirname(parent.frame(2)$ofile)

Returns: Error in dirname(parent.frame(2)$ofile) : a character vector argument expected ...because parent.frame is null

返回:dirname中的错误(parent.frame(2)$ ofile):期望的字符向量参数...因为parent.frame为null

frame_files <- lapply(sys.frames(), function(x) x$ofile)
frame_files <- Filter(Negate(is.null), frame_files)
PATH <- dirname(frame_files[[length(frame_files)]])

Returns: Null because frame_files is a list of 0

返回:Null,因为frame_files是0的列表

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))
    }
}

Returns: Error in path.expand(path) : invalid 'path' argument

返回:path.expand(path)中的错误:无效的'path'参数

Also I saw all answers from here, here, here and here. No joy.

我也看到了这里,这里,这里和这里的所有答案。没有快乐。

Working with RStudio 1.1.383

使用RStudio 1.1.383

EDIT: It would be great if there was no need for an external library to achieve this.

编辑:如果不需要外部库来实现这一点,那就太好了。

2 个解决方案

#1


18  

In RStudio, you can get the path to the file currently shown in the source pane using

在RStudio中,您可以使用获取当前在源窗格中显示的文件的路径

rstudioapi::getSourceEditorContext()$path

If you only want the directory, use

如果您只想要该目录,请使用

dirname(rstudioapi::getSourceEditorContext()$path)

If you want the name of the file that's been run by source(filename), that's a little harder. You need to look for the variable srcfile somewhere back in the stack. How far back depends on how you write things, but it's around 4 steps back: for example,

如果你想要通过源(文件名)运行的文件的名称,那就更难了。您需要在堆栈中的某处查找变量srcfile。多远取决于你如何写东西,但它大约退回4步:例如,

fi <- tempfile()
writeLines("f()", fi)
f <- function() print(sys.frame(-4)$srcfile)
source(fi)
fi

should print the same thing on the last two lines.

应该在最后两行打印相同的东西。

#2


5  

Install the here package and read the Ode to the here package.

安装here包并阅读这个包的Ode。

install.packages("here")
library(here)
here()

Documentation of the here() function:

here()函数的文档:

Starting with the current working directory during package load time, here will walk the directory hierarchy upwards until it finds a directory that satisfies at least one of the following conditions:

在程序包加载期间从当前工作目录开始,此处将向上遍历目录层次结构,直到找到满足以下至少一个条件的目录:

  • contains a file matching [.]Rproj$ with contents matching ^Version: in the first line
  • 包含匹配[。] Rproj $的文件,其内容与第一行中的^ Version:匹配
  • [... other options ...]
  • [......其他选择...]
  • contains a directory .git
  • 包含目录.git

Once established, the root directory doesn't change during the active R session. here() then appends the arguments to the root directory.

一旦建立,根目录在活动R会话期间不会更改。 here()然后将参数附加到根目录。

The development version of the here package is available on github.

这个包的开发版本可以在github上找到。

#1


18  

In RStudio, you can get the path to the file currently shown in the source pane using

在RStudio中,您可以使用获取当前在源窗格中显示的文件的路径

rstudioapi::getSourceEditorContext()$path

If you only want the directory, use

如果您只想要该目录,请使用

dirname(rstudioapi::getSourceEditorContext()$path)

If you want the name of the file that's been run by source(filename), that's a little harder. You need to look for the variable srcfile somewhere back in the stack. How far back depends on how you write things, but it's around 4 steps back: for example,

如果你想要通过源(文件名)运行的文件的名称,那就更难了。您需要在堆栈中的某处查找变量srcfile。多远取决于你如何写东西,但它大约退回4步:例如,

fi <- tempfile()
writeLines("f()", fi)
f <- function() print(sys.frame(-4)$srcfile)
source(fi)
fi

should print the same thing on the last two lines.

应该在最后两行打印相同的东西。

#2


5  

Install the here package and read the Ode to the here package.

安装here包并阅读这个包的Ode。

install.packages("here")
library(here)
here()

Documentation of the here() function:

here()函数的文档:

Starting with the current working directory during package load time, here will walk the directory hierarchy upwards until it finds a directory that satisfies at least one of the following conditions:

在程序包加载期间从当前工作目录开始,此处将向上遍历目录层次结构,直到找到满足以下至少一个条件的目录:

  • contains a file matching [.]Rproj$ with contents matching ^Version: in the first line
  • 包含匹配[。] Rproj $的文件,其内容与第一行中的^ Version:匹配
  • [... other options ...]
  • [......其他选择...]
  • contains a directory .git
  • 包含目录.git

Once established, the root directory doesn't change during the active R session. here() then appends the arguments to the root directory.

一旦建立,根目录在活动R会话期间不会更改。 here()然后将参数附加到根目录。

The development version of the here package is available on github.

这个包的开发版本可以在github上找到。