如何在RStudio未运行时从R控制台获取其安装路径以定位pandoc
rmarkdown::find_pandoc 可以在RStudio运行时无需指定任何环境变量即可找到pandoc可执行文件:
## in Rstudio !is.null(rmarkdown::find_pandoc()$dir) # [1] TRUE
但在原生R控制台运行相同命令时,得到的结果如下:
### R console !is.null(rmarkdown::find_pandoc()$dir) # [1] FALSE
查阅?rmarkdown::find_pandoc()的文档可以解释上述结果的成因:
dir: A character vector of potential directory paths under which
‘pandoc’ may be found. If not provided, this function
searches for ‘pandoc’ from the environment variable
RSTUDIO_PANDOC (the RStudio IDE will set this variable to the
directory of Pandoc bundled with the IDE), the environment
variable PATH, and the directory ‘~/opt/pandoc/’.
现在需要编写一个可在命令行运行(明确不需要在RStudio内部运行)的脚本,该脚本需要定位到pandoc才能正常运行。按照文档说明可以配置PATH环境变量保证命令行能找到pandoc,但如果要让同事也能使用该脚本,就需要确保所有人都提前配置好对应PATH,希望避免这种操作。
已确认所有使用者都安装了RStudio(但安装位置各不相同),因此如果能获取到RStudio的安装路径,就可以推导出pandoc的存放位置。
请问是否有可靠的方法,可以在RStudio未运行的状态下,从R控制台获取到RStudio的安装路径?
你不需要主动提取RStudio完整安装路径,直接通过跨平台的路径检索逻辑就能定位到RStudio绑定的pandoc,以下是可直接嵌入脚本的通用实现,无需用户做任何前置配置:
find_rstudio_pandoc <- function() { # 已找到pandoc时直接返回 if (!is.null(rmarkdown::find_pandoc()$dir)) { return(rmarkdown::find_pandoc()$dir) } os <- Sys.info()["sysname"] # 按系统生成候选路径 candidate_dirs <- switch(os, "Windows" = { # 优先读注册表获取RStudio安装路径 reg_path <- tryCatch({ hcu <- utils::readRegistry("Software\\RStudio\\RStudio", "HCU", maxdepth = 1) hlm <- utils::readRegistry("Software\\RStudio\\RStudio", "HLM", maxdepth = 1) c(hcu$InstallPath, hlm$InstallPath) }, error = function(e) NULL) # 拼接pandoc常见路径,适配新旧版RStudio pandoc_paths <- lapply(reg_path, function(p) { c(file.path(p, "resources/app/bin/quarto/bin/tools"), file.path(p, "bin/quarto/bin/tools"), file.path(p, "bin/pandoc")) }) |> unlist() # 补充系统默认安装路径 c(pandoc_paths, "C:/Program Files/RStudio/resources/app/bin/quarto/bin/tools", "C:/Program Files/RStudio/bin/pandoc", file.path(Sys.getenv("LOCALAPPDATA"), "RStudio/bin/pandoc") ) }, "Darwin" = { # macOS c("/Applications/RStudio.app/Contents/Resources/app/bin/quarto/bin/tools", "/Applications/RStudio.app/Contents/MacOS/pandoc", file.path(Sys.getenv("HOME"), "Applications/RStudio.app/Contents/MacOS/pandoc") ) }, "Linux" = { c("/usr/lib/rstudio/resources/app/bin/quarto/bin/tools", "/usr/lib/rstudio/bin/pandoc", "/usr/local/lib/rstudio/bin/pandoc", "/opt/RStudio/bin/pandoc" ) }, character(0) ) # 去重后只保留存在的目录 valid_dirs <- unique(candidate_dirs[dir.exists(candidate_dirs)]) res <- rmarkdown::find_pandoc(dir = valid_dirs) if (is.null(res$dir)) { stop("未找到绑定的pandoc,请手动配置PATH变量或检查RStudio安装") } return(res$dir) } # 调用后自动缓存pandoc路径,后续rmarkdown操作可直接使用 pandoc_path <- find_rstudio_pandoc() rmarkdown::find_pandoc(cache_dir = pandoc_path)
如果确实需要单独获取RStudio的安装路径,可提取对应系统的检索逻辑:
- Windows:直接读取注册表
HKEY_CURRENT_USER/Software/RStudio/RStudio或HKEY_LOCAL_MACHINE/Software/RStudio/RStudio下的InstallPath值即可 - macOS:检查
/Applications/RStudio.app路径是否存在即可 - Linux:检索
/usr/lib/rstudio、/usr/local/lib/rstudio等默认安装路径
内容的提问来源于stack exchange,提问作者thothal

