Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 434
Matt Bannert Avatar asked Feb 13 '23 06:02

Matt Bannert


1 Answers

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.

like image 90
shadow Avatar answered Feb 15 '23 18:02

shadow