Make R wait for console input?

不问归期 提交于 2019-12-21 20:14:54

问题


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.


回答1:


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.




回答2:


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.




回答3:


Why not putting

source("script2.R")

into the file script1.R?



来源:https://stackoverflow.com/questions/22981188/make-r-wait-for-console-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!