R readline does not work in script
Asked Answered
I

2

5

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] "" does not wait for my input. So how to fix it?

Implausibility answered 9/3, 2015 at 5:14 Comment(0)
M
5

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))
Mantelet answered 9/3, 2015 at 10:16 Comment(0)
G
3

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")
}
Gabriellegabrielli answered 9/3, 2015 at 5:42 Comment(1)
well, it's not interactive mode when running as a script in terminal. Im wondering if there is a function works - ^ -Implausibility

© 2022 - 2024 — McMap. All rights reserved.