R readline 在脚本中不起作用

yal*_* du 5 python r readline raw-input

R 中的函数readline与 python 中的函数类似raw_input,都允许传递交互式参数。

但是,当我在终端中运行 R 脚本时,它不起作用。

这是一个例子txt.R:

#!/usr/bin/env Rscript
x = readline('Hello?')
print(x)
Run Code Online (Sandbox Code Playgroud)

在终端中运行./txt.R,只打印出:

Hello? [1] "" 不等待我的输入。那么如何解决呢?

Ric*_*ler 5

我们可以readLines在从终端运行的脚本中使用。例如:

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


小智 3

不幸的是 readline() 只能在交互模式下按照您期望的方式工作。

这是来自文档 ?readline 值部分的评论

在非交互式使用中,结果就像响应是 RETURN 并且值为“”。

您可以测试一下运行此代码的模式是否是交互式的。

if(interactive()) {
    print("In interactive mode")
} else {
    print("Not in interactive mode")
}
Run Code Online (Sandbox Code Playgroud)