等待用户输入5秒钟,然后使用默认值

时间:2019-01-09 14:42:54

标签: r user-input wait

我想让用户有机会输入输入,如果他们在5秒钟后没有输入任何内容,则使用默认值。

这里是输入部分:

input <- readline(prompt="Do something? (y/n): ")

在R中有办法吗?

3 个答案:

答案 0 :(得分:2)

这是我如何完成一个窗口提示,允许用户选择要在集群中启动的线程数。它使用默认值,然后在按下“确定”按钮或经过5秒钟后继续操作。

library(tcltk2)

clusterCount = 1

tklist <- list()
tklist <- within(tklist, {
  # define processor input window
  win1 <- tktoplevel()
  rb1 <- tk2radiobutton(win1)
  rb2 <- tk2radiobutton(win1)
  rb3 <- tk2radiobutton(win1)
  rb4 <- tk2radiobutton(win1)
  rbCluster <- tclVar(clusterCount)
  tkconfigure(rb1, text = "one",  variable = rbCluster, value = 1L)
  tkconfigure(rb2, text = "two",  variable = rbCluster, value = 2L)
  tkconfigure(rb3, text = "three", variable = rbCluster, value = 3L)
  tkconfigure(rb4, text = "four", variable = rbCluster, value = 4L)
  onOK <- function() {
    clusterCount <<- as.integer(tclvalue(rbCluster))
    tkdestroy(win1)
  }
  butOK <- tk2button(win1, text = "OK", width = -8, command = onOK)

  # geometry manager
  tkgrid(tk2label(win1, text = "how many cores?"), padx = 10, pady = c(15, 5))
  tkgrid(rb1, padx = 10, pady = c(0, 5))
  tkgrid(rb2, padx = 10, pady = c(0, 15))
  tkgrid(rb3, padx = 10, pady = c(0, 15))
  tkgrid(rb4, padx = 10, pady = c(0, 15))
  tkgrid(butOK, padx = 10, pady = c(5, 15))
  tclAfter(5000, function() tkdestroy(win1)) # delay for prompt and then close window to proceed
  tkfocus(win1)
  tkwait.window(win1)
})

窗口关闭后,clusterCount将保持默认值1,或者可以更改为2、3或4。

答案 1 :(得分:1)

如果您有R的较新版本,则可以尝试使用withTimeout包中的utils函数来包装readline函数。

在基数R中有一个很难使用的函数,称为setTimeLimit

我的越野车尝试解决方案如下 这在RGui中有效,但似乎也确实使R-studio崩溃

timed_readline <- function(prompt = '',default,timeout = 10)
{
    inner <- function(timeout)    # wrapped in internal function to stop error being displayed
    {
        setTimeLimit(elapsed=timeout,transient=TRUE)
        a <- readline('')
        setTimeLimit(transient=TRUE)
        return(a)
    }

    cat(prompt)
    b <- default
    try({b <- inner(timeout)},silent=TRUE) 
    return(b)
}

因此,我不推荐此代码,但它可能会启发您一些可行的方法

答案 2 :(得分:-1)

我找不到在控制台中跳过该交互的方法。无论如何,我都留下了一个与时间有关的函数,如果您按Enter键以跳过提示,则会获得一个预定义的值。我希望这是保存控制台交互的一种方式。

#set time in seconds to get an answer from prompt 
#some interaction in console is needed, sorry

Q <- function (x) {
    t0 <- Sys.time() 
    input <- readline(prompt="Do something? (y/n): ")
    tf <- Sys.time()-t0

    if (tf > x){
        input <- "your predefined answer"
    }

    print (tf) #remove if you like
    return (input)
}

Q(5)