Interrupting readline() after a time interval in R

后端 未结 3 1561
有刺的猬
有刺的猬 2021-01-22 08:14

How to break a loop after a certain elapsed time? I have a function that collects observational data from a user. The user should have a pre-defined time limit, when the data ar

3条回答
  •  清酒与你
    2021-01-22 08:17

    I've also been looking for a solution to this, ended up writing my own function below, but it only works in some setups/platforms. The main problem is that readline suspends execution until input is provided, so it may hang indefinitely, without ever returning.

    My workaround is to open(file('stdin'), blocking=FALSE), and then use readLines(n=1). Problem with that is that it only accepts file('stdin'), which is not always connected. It fails in RGui for windows and MacOS, and for RStudio (at least for MacOS). But it seems to work for R when run from terminal under MacOS.

    readline_time <- function(prompt, timeout = 3600, precision=.1) {
      stopifnot(length(prompt)<=1, is.numeric(timeout), length(timeout)==1, !is.na(timeout), timeout>=0, is.numeric(precision), length(precision)==1, !is.na(precision), precision>0)
      if(!interactive()) return(NULL)
      if(timeout==0) return(readline(prompt))
      my_in <- file('stdin')
      open(my_in, blocking=FALSE)
      cat(prompt)
      ans <- readLines(my_in, n=1)
      while(timeout>0 && !length(ans)) {
        Sys.sleep(precision)
        timeout <- timeout-precision
        ans <- readLines(my_in, n=1)
      }
      close(my_in)
      return(ans)
    }
    

    Or if you want to import (along with some other functions): devtools::install_github('EmilBode/EmilMisc')

提交回复
热议问题