Matt Bannert
Matt Bannert

Reputation: 28264

Make R wait for console input?

Is there a way to make R wait for console input before continuing? Let's say I source two scripts like this in a main script called run.R:

# some more R Code here

source("script1.R")
source("script2.R")

# some more R Code there

Script1 contains some readLine statement that asks the user for a username. Unfortunately if I just run the entire run.R file R doesn't wait for the username to be entered. It starts script2.R before the username is entered which leads to an error because the 2nd script needs the username.

I have an ugly workaround for this using R Studio's .rs.askForPassword which actually waits for the the input, but covers the password. Which is cool for passwords, but not so much for usernames. Plus it's an RStudio feature, not R.

Upvotes: 4

Views: 5856

Answers (3)

Jianyu
Jianyu

Reputation: 31

Why not putting

source("script2.R")

into the file script1.R?

Upvotes: 0

bartektartanus
bartektartanus

Reputation: 16080

Try scan function.

This is test.R file:

y <- 2
cat('y=',y)
cat("\nEnter username")
x <- scan(what=character(),nmax=1,quiet=TRUE)
"ala ma kota"
y <- 2*2
cat('y=',y)
cat('\nx=',x)

and then I run this:

> source("test.R")
y= 2
Enter username
1: login
y= 4
x= login

--edit-- To read only one character quietly run this:

> x <- scan(what=character(),nmax=1,quiet=TRUE)
1: username
> x
[1] "username"

what sets the type, nmax sets the maximal numbers of elements to read and quiet determine if print a line, saying how many items have been read.

Upvotes: 4

shadow
shadow

Reputation: 22293

readline can only be used in interactive sessions. In non-interactive use of readline the result is an empty string. On the help page of ?interactive you find the following about interactive sessions:

GUI consoles will arrange to start R in an interactive session. When R is run in a terminal (via Rterm.exe on Windows), it assumes that it is interactive if ‘stdin’ is connected to a (pseudo-)terminal and not if ‘stdin’ is redirected to a file or pipe. Command-line options --interactive (Unix) and --ess (Windows, Rterm.exe) override the default assumption.

Upvotes: 4

Related Questions