简体   繁体   中英

R readline does not work in script

The function readline in R is similar to raw_input in python, both allow to pass interactive arguments.

However, when I run a R script in terminal, It does not work.

Here is a example txt.R :

#!/usr/bin/env Rscript
x = readline('Hello?')
print(x)

Run ./txt.R in terminal, it just print out:

Hello? [1] "" Hello? [1] "" does not wait for my input. So how to fix it?

We can use readLines in scripts run from the terminal. For example:

#!/usr/bin/env Rscript
cat("What is your name? ")
x <- readLines("stdin", 1)
cat(sprintf("Hello, %s!\n", x))

Unfortunately readline() will work the way you expect only in interactive mode.

Here is a comment from the documentation ?readline in the value section

In non-interactive use the result is as if the response was RETURN and the value is "".

You can test to see if the mode in which you are running this code is interactive.

if(interactive()) {
    print("In interactive mode")
} else {
    print("Not in interactive mode")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM