我怎么只能追踪一次?

时间:2019-05-06 11:06:33

标签: r debugging

就像我们可以使用debugonce而不是debug / undebug那样,最好使用traceonce函数而不是{ {1}} / trace

我们该怎么做?

1 个答案:

答案 0 :(得分:0)

这是我想出的:

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种情况,是否存在) )添加对给定函数的untrace的调用。


带有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