让Rscript读取或从stdin接受输入 [英] Have an Rscript read or take input from stdin

查看:74
本文介绍了让Rscript读取或从stdin接受输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I see how to have an Rscript perform the operations I want when given a filename as an argument, e.g. if my Rscript is called script and contains:

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

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

Then I can run from the bash command line:

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

并成功获取 filename.Rmd 的内容回显给我.如果不是要传递上述参数作为文件名,例如 filename.Rmd ,而是要从 stdin 传递文本,我尝试修改脚本以从stdin读取:

and successfully get the contents of filename.Rmd echoed back out to me. If instead of passing the above argument a filename like filename.Rmd I want to pass it text from stdin, I try modifying my script to read from stdin:

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

但是对于这种情况,我不知道如何构造命令行调用.我在内容中尝试了管道:

but I do not know how to construct the commandline call for this case. I tried piping in the contents:

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

并尝试重定向:

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

以及我收到错误的任何一种方式:

and either way I get the error:

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

(我也尝试过 open(file("stdin"))).我不确定我是错误地构造了Rscript还是命令行参数不正确,或两者都没有.

(I've also tried open(file("stdin"))). I'm not sure if I'm constructing the Rscript incorrectly, or the commandline argument incorrectly, or both.

推荐答案

您需要从 file("stdin")创建的连接中读取文本,以便将有用的内容传递给 writeLines()的> text 自变量.这应该工作

You need to read text from the connection created by file("stdin") in order to pass anything useful to the text argument of writeLines(). This should work

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

这篇关于让Rscript读取或从stdin接受输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆