问题
When I try the following:
f<-file("stdin")
lines<-readLines(f)
from within R-studio on Ubuntu I can input text but unable to terminate it. Ctr+C/D, random hitting keyboard won't help. It simply hangs
I only found the followin so far How to input EOF in stdin in R? but no help there - had to kill R-studio.
Anybody have explanation what is wrong?
回答1:
Presumably, Rstudio is redirecting stdin, so that it cannot be properly accessed as "stdin" or "/dev/stdin" any longer. However, stdin() still works.
I was still unable to actually type Ctrl+D. But it is possible to read a fixed number of lines:
> a <- readLines(stdin(), n=2)
Hello
World
> a
[1] "Hello" "World"
I've also discovered a hack that may help for interactive debugging. Let's say, you have at most 10 lines in your manual examples. Then you can do
> a <- readLines(stdin(), n=10)
abc
def
ghi
# and now just keep pressing ENTER
...
> a <- a[a != ""]
> a
[1] "abc" "def" "ghi"
If you run the same code in an environment where Ctrl+D is available, it also properly terminates the input.
Caveats: but stdin() does not work with Rscript: you'd have to switch back to file("stdin"). Furthermore, in some environments, if you use readLines with n=1 to read the file line-by-line, you may end up reopening the file and getting the first line every time. It seems that putting everything into a file and reading the whole file at once with e.g. read.table is a much more robust way of developing with Rstudio.
来源:https://stackoverflow.com/questions/30191232/use-stdin-from-within-r-studio