taskhandler that executes *before* the expr

╄→гoц情女王★ 提交于 2019-12-10 18:59:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!