如何仅在满足条件时启动调试器

问题描述 投票:3回答:2

假设我有一个函数,它使用整数i上的循环。现在出了问题,我认为错误发生在i=5。现在我可以逐步完成每一步(我现在所做的)。

但是现在我读到了关于conditiontextbrowserdebug论点:

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()
}

正在工作,但我认为可能有更好的东西(函数内没有额外的代码)

r debugging condition
2个回答
3
投票

你可以在expr中使用browser()参数:

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)

3
投票

使用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]>

所以

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.