R-我只能仅追踪一次

  • 本文关键字:一次 追踪 r debugging
  • 更新时间 :
  • 英文 :


就像我们拥有可以使用的debugonce代替debug/undebug夫妇一样,使用traceonce函数而不是trace/untrace

我们该怎么做?

这就是我想到的:

traceonce <- function(what, tracer, exit, at, print, signature,
                       where = topenv(parent.frame()), edit = FALSE){
  mc <- match.call()
  mc[[1]] <- quote(trace)
  mc[["exit"]] <-
    if (missing(exit)) substitute(quote(eval.parent(quote(untrace(what)))))
    else c(as.expression(exit), substitute(eval.parent(quote(untrace(what)))))
  eval.parent(mc)
}

我编辑了调用的形式,这样我就不必在missing上处理一堆检查,然后我编辑呼叫的exit元素(是否存在2个情况,是否存在(即可添加一个呼叫呼叫给定功能。


使用exit参数:

traceonce(head, exit = quote({print("hello")}))
#> Tracing function "head" in package "utils"
#> [1] "head"
head(cars,1)
#> Tracing head(cars, 1) on exit 
#> [1] "hello"
#> Untracing function "head" in package "utils"
#>   speed dist
#> 1     4    2
head(cars,1)
#>   speed dist
#> 1     4    2

没有exit参数:

traceonce(head, quote({print("hello")}))
#> Tracing function "head" in package "utils"
#> [1] "head"
head(cars,1)
#> Tracing head(cars, 1) on entry 
#> [1] "hello"
#> Tracing head(cars, 1) on exit
#> Untracing function "head" in package "utils"
#>   speed dist
#> 1     4    2
head(cars,1)
#>   speed dist
#> 1     4    2

最新更新