4

I am searching for a way to get user input inside a loop while executing in batch mode.

readLines() and scan() work well for me in interactive mode only, in batch mode they start to read in lines of code as user input, unless all the code is surrounded by {}, which is inconvenient. I need a simple solution to get just 1 integer value in a way that I can just type in value and press ENTER, so

  1. the input field (if the solution involves GUI) must automatically get focus and
  2. ENTER must trigger end of input/submission.

I can't find a way to do it that will satisfy both conditions, e.g. ginput() from gWidgets activates the input field, but ENTER doesn't trigger form submission.

user1603038
  • 2,103
  • 3
  • 19
  • 29

2 Answers2

2

Here is how I solved my own problem:

require(gWidgets)
options(guiToolkit="RGtk2")

INPUT <- function(message) {
  CHOICE <- NA
  w <- gbasicdialog(title=message, handler = function(h,...) CHOICE <<- svalue(input))
  input <- gedit("", initial.msg="", cont=w, width=10)
  addHandlerChanged(input, handler=function (h, ...) {
    CHOICE <<- svalue(input)
    dispose(w)
  })
  visible(w, set=TRUE)
  return(CHOICE)
}

repeat{
  x=INPUT("Input an integer")
  if(!is.na(as.integer(x))) break
}
print(x)
user1603038
  • 2,103
  • 3
  • 19
  • 29
1

Update:

I can't test this right now, but take a look at ?menu and have it pop up a gui window.
I'm not certain if that will work, but it is different in that it takes a mouse-click response.


original answer:

As per the documentation to ?readline:

This can only be used in an interactive session.
..
In non-interactive use the result is as if the response was RETURN and the value is "".

If you are simply waiting for one piece of information, and you do not know this piece of information before beginning the execution of the script (presumably, there is a decision to be made which is dependent on the results earlier in the script), then one alternative is to simply break your script up into three parts:

  • everything before the decision point.
  • an interactive script which prompts for input
  • everything after the decision point.

And simply chain the three together by having the first end by calling the second in an interactive session. Then have the second end by calling the third.

Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178