r语言 - 等待用户输入 5 秒钟,否则使用默认值



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

这是输入部分:

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

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

以下是我如何完成窗口提示,允许用户选择要在群集中启动的线程数。 它使用默认值,然后在按下确定按钮或 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。

如果你有较新版本的R,那么你可以尝试从utils包中withTimeout函数来包装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)
}

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

我找不到在控制台中跳过该交互的方法。无论如何,我将留下一个关于时间的函数,如果您按 Enter 退出时间以跳过 promt,您将获得一个预定义的值。我希望这是一种保存控制台交互的方法。

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

相关内容

  • 没有找到相关文章

最新更新