You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R脚本嵌套source后无法获取A.R路径返回NULL,求解决方案

问题与解决方法

问题场景

我创建了三个R脚本:

  • A.R:定义get_file_location()函数用于获取脚本路径,最后尝试输出自身文件名
  • B.R:仅执行source("A.R")
  • C.R:仅执行source("B.R")

执行source("C.R")时,期望输出Path of script A is: A.R,但实际返回NULL。

各脚本原始代码

A.R

get_file_location <- function() {
  # Attempts to get the file path in RStudio
  if (interactive() && "rstudioapi" %in% rownames(installed.packages())) {
    return(rstudioapi::getSourceEditorContext()$path)
  }

  # Alternative to get the file path if source() is used
  this_file <- (function() { attr(body(sys.function(1)), "srcfile") })()

  # If the path cannot be retrieved (e.g., in the console without RStudio), assign a default value
  if (!is.null(this_file)) {
    return(this_file$filename)
  } else {
    return("File not specified or default path")
  }
}

code_name <- get_file_location() %>% str_split_1(., pattern = "/") %>% tail(., 1)

paste("Path of script A is: ", code_name )

B.R

source("A.R")

C.R

source("B.R")

问题原因

当通过多层source调用时,sys.function(1)指向的是最外层的调用栈(即执行source("C.R")的上下文),而非A.R的执行环境,导致attr(body(sys.function(1)), "srcfile")无法获取到A.R的文件路径,最终返回NULL。

解决方法

修改A.R的代码,在脚本顶层直接捕获自身路径(此时执行环境是A.R被source时的上下文,能正确拿到A.R的路径),而不是在函数调用时动态查找:

# 在A.R顶层直接获取当前脚本路径
current_script_path <- (function() {
  src <- attr(sys.call(), "srcfile")
  if (!is.null(src)) {
    return(src$filename)
  } else {
    return("File not specified or default path")
  }
})()

get_file_location <- function() {
  # RStudio交互环境下优先使用rstudioapi获取路径
  if (interactive() && "rstudioapi" %in% rownames(installed.packages())) {
    return(rstudioapi::getSourceEditorContext()$path)
  }
  # 非交互环境直接返回顶层捕获的路径
  return(current_script_path)
}

# 提取文件名并输出
code_name <- current_script_path %>% str_split_1(pattern = "/") %>% tail(1)
cat("Path of script A is: ", code_name, "\n")

修改后,无论通过B.R还是C.R调用source,A.R的顶层代码在执行时都会捕获到自身的文件路径,最终输出预期结果。


内容的提问来源于stack exchange,提问作者Nachengue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:41:03