【问题标题】:Have an Rscript read or take input from stdin让 Rscript 读取或从标准输入获取输入
【发布时间】:2014-04-01 20:41:14
【问题描述】:

当给定文件名作为参数时,我看到了如何让 Rscript 执行我想要的操作,例如如果我的 Rscript 被称为 script 并包含:

#!/usr/bin/Rscript 
path <- commandArgs()[1]
writeLines(readLines(path))

然后我可以从 bash 命令行运行:

Rscript script filename.Rmd --args dev='svg'

并成功地将filename.Rmd 的内容回显给我。如果不是将上述参数传递给filename.Rmd 之类的文件名,而是想从stdin 传递文本,我尝试修改我的脚本以从标准输入读取:

#!/usr/bin/Rscript 
writeLines(file("stdin"))

但我不知道如何为这种情况构建命令行调用。我尝试在内容中添加管道:

cat filename.Rmd | Rscript script --args dev='svg'

还尝试了重定向:

Rscript script --args dev='svg' < filename.Rmd

无论哪种方式我都会收到错误:

Error in writeLines(file("stdin")) : invalid 'text' argument

(我也试过open(file("stdin")))。我不确定我是在错误地构建 Rscript,还是错误地构建了命令行参数,或者两者兼而有之。

【问题讨论】:

  • Piping stdin to R 的可能重复项
  • 但您的错误可能是使用 writeLines 读取 vs readLines
  • 谢谢;使用readLines(file("stdin")) 代替open(file("stdin")) 解决了我的问题。

标签: r bash stdin


【解决方案1】:

您需要从file("stdin") 创建的连接中读取文本,以便将任何有用的信息传递给writeLines()text 参数。这应该工作

#!/usr/bin/Rscript 
writeLines(readLines(file("stdin")))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-30
    • 2012-02-17
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    相关资源
    最近更新 更多