问题 R:提供5秒钟要求暂停。如果没有要求暂停,请恢复该过程


我怎样才能为用户提供5秒的时间来写一些东西以便请求无限长的暂停。如果在这5秒内没有要求暂停,则该过程继续。如果需要暂停,则用户具有他需要的所有时间以及他可以点击“输入”以便随时恢复该过程。

这种功能的兴趣在于如果用户不在,则暂停仅持续5秒。并且如果用户在场,那么他可以享受暂停以便观看例如已经产生的图表。

代码最终可能看起来像这样:

DoYouWantaPause = function(){
   myprompt = "You have 5 seconds to write the letter <p>. If you don't the process will go on."

   foo = readline(prompt = myprompt, killAfter = 5 Seconds)    # give 5 seconds to the user. If the user enter a letter, then this letter is stored in `foo`.

   if (foo == "p" | foo == "P") {    # if the user has typed "p" or "P"
        foo = readline(prompt = "Press enter when you want to resume the process")  # Offer a pause of indefinite length
   }
}

# Main
for (i in somelist){
    ...
    DoYouWantaPause()
}

2255
2017-12-10 20:18


起源

在尝试新事物之前阅读文档的第一个理由: ?R.utils::withTimeout: Furthermore, it is not possible to interrupt/break out of a "readline" prompt (e.g. readline() and readLines()) using timeouts; the timeout exception will not be thrown until after the user completes the prompt (i.e. after pressing ENTER). - rawr
是的,我知道没有意义,但解释我的需求是有帮助的。感谢您提供的文档副本。 - Remi.b


答案:


这是一个基于tcltk和tcltk2包的快速小功能:

library(tcltk)
library(tcltk2)

mywait <- function() {
    tt <- tktoplevel()
    tmp <- tclAfter(5000, function()tkdestroy(tt))
    tkpack( tkbutton(tt, text='Pause', command=function()tclAfterCancel(tmp)))
    tkpack( tkbutton(tt, text='Continue', command=function()tkdestroy(tt)),
        side='bottom')
    tkbind(tt,'<Key>', function()tkdestroy(tt) )

    tkwait.window(tt)
    invisible()
}

mywait 如果你什么都不做的话,会弹出一个带有2个按钮的小窗口,然后大约5秒后窗口就会消失 mywait 将返回允许R继续。如果您随时点击“继续”,它将立即返回。如果您单击“暂停”,则倒计时将停止,它将等待您单击继续(或按键),然后继续。

这是给出答案的延伸 这里


10
2017-12-10 21:04



甜!这非常有效。非常感谢! - Remi.b