Have an Rscript read or take input from stdin

北城余情 提交于 2019-12-08 17:38:11

问题


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))

Then I can run from the bash command line:

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

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'

and also tried redirect:

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

and either way I get the error:

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

(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.


回答1:


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")))


来源:https://stackoverflow.com/questions/22796434/have-an-rscript-read-or-take-input-from-stdin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!