问题描述
在JavaScript中,我可以使用console.log(new Error().stack)
或console.trace()
来显示堆栈跟踪。
R中是否有类似的东西?我可以显示函数在我的位置调用stacktrace吗。我的应用程序很复杂,很难跟踪所调用的代码,显示调用函数的stacktrace可以简化代码的执行方式。
我已经尝试过这种方法:
foo <- function() bar()
bar <- function() {
tryCatch(
stop('nop'),error = function(e) {
print(traceback(e))
})
}
foo()
但是它不起作用,我需要在顶层捕获错误才能看到该堆栈。是否有简单的函数在调用时会显示堆栈帧?
编辑: 这是一个示例,它在JavaScript中是什么样子,这是我希望它如何工作,在R中是否有类似的可能?
function foo() {
bar();
}
function bar() {
baz();
}
function baz() {
// console.trace is dev tools function
// this will show up the stack if open dev tools and then run the snippet
console.trace();
console.log(new Error().stack);
}
foo();
如您所见,未引发错误,它只是创建一个对象,浏览器会将调用的堆栈跟踪添加到该对象,以便可以对其进行检查。
解决方法
如果您想查看调用堆栈而不会引发错误,则可以尝试如下操作:
show_stack <- function() {
cat("#----- Stack containing call to show_stack -----#\n\n")
x <- sys.calls()
lapply(head(x,-1),function(x) {print(x); cat("\n")})
cat("#-----------------------------------------------#\n\n")
}
只需在要跟踪的函数中插入
:foo <- function() bar()
bar <- function() baz()
baz <- function() show_stack()
结果:
foo()
#> #----- Stack containing call to show_stack -----#
#>
#> foo()
#>
#> function() bar()
#>
#> function() baz()
#>
#> #-----------------------------------------------#
或者,对于更真实的示例:
my_mean <- function(x) {
show_stack()
sum(x)/length(x)
}
在一次通话中可能多次运行:
tapply(iris$Sepal.Length,iris$Species,my_mean)
#> #----- Stack containing call to show_stack -----#
#>
#> tapply(iris$Sepal.Length,my_mean)
#>
#> lapply(X = ans[index],FUN = FUN,...)
#>
#> FUN(X[[i]],...)
#>
#> #-----------------------------------------------#
#>
#> #----- Stack containing call to show_stack -----#
#>
#> tapply(iris$Sepal.Length,...)
#>
#> #-----------------------------------------------#
#>
#> setosa versicolor virginica
#> 5.006 5.936 6.588