问题
Is there a callback for running code before a prompt-entered expr
is evaluated? (A search through SO, CRAN, and some googling has turned up what I suspect the answer to be: not possible with the current REPL implementation. My apologies if I missed a similarly-detailed duplicate discussion.)
I'm loosely familiar with addTaskCallback()
and its family of functions. Reading the help and developer docs tells me that the mechanism only runs after an expression is evaluated.
One eventual implementation is to provide a timing mechanism (either using system.time()
or something more mundane); current methods (such as this) are helpful yet knowingly unaware of idle time.
Perhaps something akin to:
timerFunc <- local({
.time <- 0
function(expr, value, ok, visible) {
if (missing(value)) {
# called pre-evaluate
.time <<- as.numeric(Sys.time())
} else {
# called post-evaluate
gap <- as.numeric(Sys.time()) - .time
if ( gap >= 10 ) {
cat("##", gap, "seconds\n")
# do something useful/meaningful
}
}
return(TRUE)
}
})
## this function does not exist (yet)
addPreTaskCallback(timerFunc)
## but this one does
addTaskCallback(timerFunc)
(This is merely example code without robustness and with a magic constant ... provided with brevity for discussion.)
I can think of several other contrived examples of how this could be used; though most are educational/academic, they are also arguably inefficient or lazy.
I'm guessing the overwhelming response will be "this should be on R-devel." If so, I believe this would attach somehow to R_ReadConsole
(explained in R-exts). Thoughts?
来源:https://stackoverflow.com/questions/22994168/taskhandler-that-executes-before-the-expr