R readline在scrip中不起作用

2024-05-08 16:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

R中的函数readline类似于python中的raw_input,两者都允许传递交互参数。在

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

下面是一个示例txt.R

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

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

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


Tags: 函数envtxt脚本终端示例helloinput
2条回答

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

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

不幸的是,readline()只能在交互模式下以预期的方式工作。在

这是文档中的注释?值部分的readline

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

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

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

相关问题 更多 >