![](/img/trans.png)
[英]graphics window invoked from r command prompt but not with rscript.exe
[英]Is there a way to debug an R script run from the command line with Rscript.exe
是否可以調試使用 Rscript.exe 執行的 R 源文件?
> Rscript.exe mysource.R various parameters
理想情況下,我希望能夠在 RStudio 的 mysource.R 文件中的某處設置斷點。是否可以直接在命令行輸入 R 調試器,例如通過向源文件添加一些調試指令?
也許從 R 獲取文件可行? 如何? 如何傳遞命令行 arguments“各種參數”,以便 commandArgs() 返回正確的值?
mysource.R 可能如下所示(實際上要復雜得多)。
#!/usr/bin/Rscript
args <- commandArgs(trailingOnly=TRUE)
print(args)
至於從控制台進行調試,幾乎沒有與之相關的問題。
有沒有一種方法可以在RStudio中調試RScript調用? 和Rscript調試使用命令行
因此,我不確定是否有所更改以及現在是否有可能。
但是,我們可以使用黑客手段從文件源中進行調試。 您可以在要調試的任何位置在文件中添加browser()
。 將您的主文件視為:
主R
args <- commandArgs(trailingOnly=TRUE)
browser()
print(args)
現在,我們可以覆蓋commandArgs
函數,並傳遞我們要傳遞的任何參數,當您獲取文件時將傳遞這些參數。
調用文件
commandArgs <- function(...) list(7:9, letters[1:3])
source("main.R")
運行source
命令后,您可以從那里調試
Called from: eval(ei, envir)
#Browse[1]> args
#[[1]]
#[1] 7 8 9
#[[2]]
#[1] "a" "b" "c"
沒有在命令行中調試 Rscript 的本機方法,但您可以使用我用readLines
和eval
提出的一種 hacky 解決方法。
ipdb.r <- function(){
input <- ""
while(!input %in% c("c","cont","continue"))
{
cat("ipdb.r>")
# stdin connection to work outside interactive session
input <- readLines("stdin",n=1)
if(!input %in% c("c","cont","continue","exit"))
{
# parent.frame() runs command outside function environment
print(eval(parse(text=input),parent.frame()))
}else if(input=="exit")
{
stop("Exiting from ipdb.r...")
}
}
}
使用 Rscript 調用的 R 文件中的示例用法:
ipdbrtest.R
a <- 3
print(a)
ipdb.r()
print(a)
命令行:
$ Rscript ipdbrtest.R
[1] 3
ipdb.r>a+3
[1] 6
ipdb.r>a+4
[1] 7
ipdb.r>a <- 4
[1] 4
ipdb.r>c
[1] 4
如果您正在考慮使用 R 而不是 Rscript,您可以將環境變量傳遞給它並使用Sys.getenv()
檢索它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.