Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can code execution be paused until a key is pressed?

I'm trying to get R to pause code execution, for the user to review some prior console output, to verify that file links have been correctly matched (using RegEx to match file names to their respective objects).

From some other answers, I've come up with:

readline(prompt="Press [enter] to continue or [esc] to exit")

As a stand alone line of code, this works as expected, but as soon as I add code below it, and send the whole block to the console, it runs right through the readline call without stopping:

readline(prompt="Press [enter] to continue or [esc] to exit")

x <- 1
y <- 2

Is there a way to get R to actually pause here?

I've also tried wrapping readline in a function, but it still doesn't work

pause <- function(){
 p <- readline(prompt="Press [enter] to continue or [esc] to exit")
 return(p)
}

pause()

x <- 1
y <- 2

Edit:

If I call the script via source(), readline does work properly. Is there a way to get that behavior without doing that?

like image 323
Mako212 Avatar asked Oct 17 '22 16:10

Mako212


1 Answers

By "send the whole block to the console", it sounds like you are copy-pasting your code into a running R instance.

If you do that, R will run each line in the order it receives it, as soon as it receives it. If any of the lines tries to take input, that input will come from whatever you are copy-pasting. So if you copy-paste this:

readline(prompt="Press [enter] to continue or [esc] to exit")

x <- 1
y <- 2

R will read and run the first line first. That first line will run and read the next line of input (which is a blank line here). Then R will come back and read and execute the other two lines.

You need to get your code entered into R completely before any of it runs. Try wrapping the whole thing in a function:

dostuff <- function(){
    readline(prompt="Press [enter] to continue or [esc] to exit")
    x <- 1
    y <- 2
}
dostuff()
like image 150
interfect Avatar answered Oct 31 '22 15:10

interfect