[英]How can a script find itself in R running from the command line?
我有一個腳本(稱之為Main.R
),它有以下代碼在運行時找到它自己:
frame_files <- lapply(sys.frames(), function(x) x$ofile)
frame_files <- Filter(Negate(is.null), frame_files)
main.dir <- dirname(dirname(frame_files[[length(frame_files)]]))
這用於獲取其自己的目錄main.dir
上方的目錄,該目錄用於調用與此路徑相關的其他腳本。
例如,我對從命令行運行此腳本感興趣
R CMD BATCH Main.R
要么
Rscript Main.R
不幸的是,當我從命令行調用腳本時,上面的命令不起作用。
我可以在Main.R
任何代碼,還是可以使用R
或Rscript
的調用選項代替?
更具體地說,該解決方案需要在Windows中運行。
下面是一個解決方案,當使用source
或Rscript運行腳本時,它將為您提供正確的文件目錄路徑。
# this is wrapped in a tryCatch. The first expression works when source executes, the
# second expression works when R CMD does it.
full.fpath <- tryCatch(normalizePath(parent.frame(2)$ofile), # works when using source
error=function(e) # works when using R CMD
normalizePath(unlist(strsplit(commandArgs()[grep('^--file=', commandArgs())], '='))[2]))
dirname(full.fpath)
關鍵是normalizePath
函數。 給定相對或縮寫的路徑名, normalizePath
將返回有效路徑或引發錯誤。 從Rscript運行腳本時,如果為normalizePath
提供當前腳本的基本文件名,它將返回完整路徑,無論您當前的目錄是什么。 當你提供R CMD的相對路徑並且當前目錄中有一個同名的腳本時,它甚至可以獲得正確的路徑!
在上面的代碼中,我從commandArgs
返回的一個字符串中提取文件名。 如果你看一下commandArgs
的輸出,你會看到文件名是第四個參數。 參數記錄為'--file = yourscript.R',因此在上面的最后一行中,我將字符串拆分為'='並拉出文件名。
理念是將路徑作為Main.R的參數
我假設你用RScript調用它。
Rscript Main.R 'path'
在Main.R中添加代碼以讀取參數
args <- commandArgs(trailingOnly = TRUE)
mainpath <- as.character(args[1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.