簡體   English   中英

如何僅在滿足條件時啟動調試器

[英]How to start debugger only when condition is met

假設我有一個使用整數i循環的函數。 現在出了問題,我認為當i=5時會發生錯誤。 現在我可以逐步完成每一步(我現在所做的)。

但是現在我讀到了browserdebugconditiontext參數:

text一個文本字符串,可在輸入瀏覽器時檢索。
條件可以在輸入瀏覽器時檢索的條件。

是否可以按照我想要的方式使用參數?

這是一個例子。 調試器/瀏覽器只應在達到i=5后啟動:

fun <- function(x, y, n) {
  result <- 0
  for (i in 1:n) {
    # browser(condition = (i == 5)) # does not work
    result <- result + i * ( x + y)
  }
  return(result)
}

x <- 2
y <- 3
n <- 10

# debug(fun, condition = (i == 5)) # does not work
debug(fun)
r <- fun(x, y, n)
print(r)

解決方案

if (i == 5) { # inside loop of fun()
  browser()
}

正在工作,但我可能會有更好的東西(函數內沒有額外的代碼)

您可以在browser()使用參數expr

fun <- function(x, y, n) {
  result <- 0
  for (i in 1:n) {
    browser(expr = {i == 5})
    result <- result + i * ( x + y)
  }
  return(result)
}

然后它將僅打開調用browser()的環境,如果表達式的計算結果為TRUE

如果要使用debug()

debug(fun, condition = i == 5)

然后調用函數:

fun <- function(x, y, n) {
  result <- 0
  for (i in 1:n) {
    result <- result + i * ( x + y)
  }
  return(result)
}

fun(x, y, n)

使用trace()高級功能。

首先,根據at =的參數的幫助頁面說明,確定要調試的函數行,導致at = list(c(3, 4))

> as.list(body(fun))
[[1]]
`{`

[[2]]
result <- 0

[[3]]
for (i in 1:n) {
    result <- result + i * (x + y)
}

[[4]]
return(result)

> as.list(body(fun)[[3]])
[[1]]
`for`

[[2]]
i

[[3]]
1:n

[[4]]
{
    result <- result + i * (x + y)
}

接下來,通過提供一個未評估的表達式作為tracer=參數來指定條件斷點,該表達式在滿足特定條件時調用瀏覽器, tracer = quote(if (i == 3) browser())

所以

> trace(fun, tracer = quote(if (i == 3) browser()), at=list(c(3, 4)), print=FALSE)
[1] "fun"
> r <- fun(x, y, n)
Called from: eval(expr, p)
Browse[1]> 
debug: {
    result <- result + i * (x + y)
}
Browse[2]>  i
[1] 3
Browse[2]> result
[1] 15
Browse[2]> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM