How to include interactive input in script to be run from the command line

前端 未结 3 501
耶瑟儿~
耶瑟儿~ 2020-12-01 03:47

I am trying to write an interactive R script. For example:

try.R:

print(\"Entr some numbers. >\",quote=F)
a = scan(what=double(0))
print a
q()


        
相关标签:
3条回答
  • 2020-12-01 04:22

    Try this:

    cat("What's your name? ")
    x <- readLines(file("stdin"),1)
    print(x)
    

    Hopefully some variant of that works for you.

    0 讨论(0)
  • 2020-12-01 04:40

    What worked for me on Windows with RStudio 0.98.945 and R version 3.1.1 was:

        cat("What's your name? ")
        x <- readLines(con=stdin(),1)
        print(x)
    
    0 讨论(0)
  • 2020-12-01 04:42

    The answer by @Joshua Ulrich is fine for Linux, but hangs under macOS and needs to be terminated using Ctrl-D.

    This is a work-around for both Linux and macOS:

    #!/usr/bin/env Rscript
    
    print(system("read -p 'Prompt: ' input; echo $input", intern = TRUE))
    
    0 讨论(0)
提交回复
热议问题