Ite*_*tor 13 debugging r function
我试图isdebugged()
在R中找到一个全局对应物.我的场景是我有一些函数可以调用其他函数,所有这些函数都是我编写的,而且我debug()
在调试期间打开和关闭不同的函数.但是,我可能会忘记将哪些功能设置为要调试.当我忘记并开始循环时,我可能会获得更多输出(令人讨厌,但并不可怕),或者在需要某些输出时可能没有输出(坏).
我目前的方法是使用类似于下面的函数,我可以用它来调用它listDebugged(ls())
或列出已加载库中的项目(下面的例子).这可能就足够了,但它要求我用工作区中的每个函数列表或加载的包中调用它.我可以包装另一个获取这些功能的函数.看起来应该有一种更简单的方法来直接"询问"调试函数或查询环境的一些模糊部分,它隐藏了调试标志集的函数列表.
所以,这是一个两部分的问题:
我意识到还有另一种我可以尝试的方法,那就是在函数中包装debug
并undebug
维护一个隐藏的调试函数名列表.我还不相信这是安全的事情.
更新(8/5/11):我搜索了SO,但没有找到早期的问题.然而,SO的"相关问题"列表显示了一个类似的早期问题,尽管该问题的答案中的函数比@cbeleites提供的函数更冗长,更慢.较旧的问题也没有提供任何代码,而我做了.:)
代码:
listDebugged <- function(items){
isFunction <- vector(length = length(items))
isDebugged <- vector(length = length(items))
for(ix in seq_along(items)){
isFunction[ix] <- is.function(eval(parse(text = items[ix])))
}
for(ix in which(isFunction == 1)){
isDebugged[ix] <- isdebugged(eval(parse(text = items[ix])))
}
names(isDebugged) <- items
return(isDebugged)
}
# Example usage
listDebugged(ls())
library(MASS)
debug(write.matrix)
listDebugged(ls("package:MASS"))
Run Code Online (Sandbox Code Playgroud)
这是我在listDebugged函数中的抛出:
ls.deb <- function(items = search ()){
.ls.deb <- function (i){
f <- ls (i)
f <- mget (f, as.environment (i), mode = "function",
## return a function that is not debugged
ifnotfound = list (function (x) function () NULL)
)
if (length (f) == 0)
return (NULL)
f <- f [sapply (f, isdebugged)]
f <- names (f)
## now check whether the debugged function is masked by a not debugged one
masked <- !sapply (f, function (f) isdebugged (get (f)))
## generate pretty output format:
## "package::function" and "(package::function)" for masked debugged functions
if (length (f) > 0) {
if (grepl ('^package:', i)) {
i <- gsub ('^package:', '', i)
f <- paste (i, f, sep = "::")
}
f [masked] <- paste ("(", f [masked], ")", sep = "")
f
} else {
NULL
}
}
functions <- lapply (items, .ls.deb)
unlist (functions)
}
Run Code Online (Sandbox Code Playgroud)
package::function
(或者更确切namespace::function
但是包很快就会有命名空间)."(package::function)"