等待用户输入 5 秒,否则使用默认值

Wait for a user input for 5 seconds and use a default value otherwise

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

这里是输入部分:

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

有没有办法在 R 中做到这一点?

我找不到在控制台中跳过该交互的方法。不管怎样,我要留下一个关于时间的函数,如果你按时间输入以跳过提示,你将得到一个预定义的值。我希望这是一种保存控制台交互的方法。

#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)

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

在 base 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)
}

因此我不能推荐此代码,但它可能会激发您一些可行的东西

下面是我如何完成 window 提示,允许用户 select 在集群中启动的线程数。它使用默认值,然后在按下 OK 按钮或 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)
})

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