流系统()输出到Shiny前端(连续)

时间:2018-06-01 20:29:34

标签: r shell shiny stream command-line-interface

如何捕获正在进行的system() operation的输出并将其流式传输到Shiny前端,实时"?

intern=T以字符向量捕获整个输出,但我更喜欢" listen"发生时系统输出。

library(shiny) 
ui <- fluidPage(
   titlePanel("Stream the system output"),
   sidebarLayout(
      sidebarPanel(
         actionButton("btn1",label = "Let's stream")
      ),
      mainPanel(
         textOutput("textstream_output")
      )
   )
)
server <- function(input, output, session) {
  rv <- reactiveValues("textstream"=c(""))
  output$textstream_output <- renderText({
    rv$textstream
  })
  observeEvent(input$btn1,{
  # problem: is evaluated after finish, not during operation  
    rv$textstream <- system("Rscript -e \"for(i in 1:5){ print(Sys.time()); Sys.sleep(1);  };\"",
                            intern = T)
  })
}
shinyApp(ui = ui, server = server)

使用system运行intern=F命令时,R控制台每秒持续更新一次。如何在Shiny中建立它,理想情况下无需将system调用分成更小的块?

enter image description here

可能相关:

1 个答案:

答案 0 :(得分:3)

reactiveTimer提供了一种方法。我的猜测是你的方法不起作用,因为observeEvent只有在表达式的评估完成后才更新被动对象。这是我的方法。我创建了一个我想在后台运行的脚本so_script.R,并将输出转移到so_output.txt。我们希望在脚本运行时看到so_output.txt的内容。

cat('sink(file = "so_output.txt")
  for (i in 1:10) {
    cat(format(Sys.time(), format = "%H:%M:%S"), "\n")
    Sys.sleep(1)
  }
  cat("*** EOF ***\n")
  sink()
', file = "so_script.R")

这里是Shiny app:

library(shiny) 
ui <- fluidPage(
   titlePanel("Stream the system output"),
   sidebarLayout(
      sidebarPanel(
         actionButton("btn_start",label = "Let's stream"),
         actionButton("btn_stop",label = "Stop")
      ),
      mainPanel(
         htmlOutput("textstream_output")
      )
   )
)
server <- function(input, output, session) {
  rv <- reactiveValues(textstream = c(""),
                       timer = reactiveTimer(1000),
                       started = FALSE)
  observeEvent(input$btn_start, { 
    rv$started <- TRUE
    system2("Rscript", "so_script.R", wait = FALSE)
  })
  observeEvent(input$btn_stop, { rv$started <- FALSE })
  observe({
    rv$timer()
    if (isolate(rv$started))
      rv$textstream <- paste(readLines("so_output.txt"), collapse = "<br/>")
  })
  output$textstream_output <- renderUI({
    HTML(rv$textstream)
  })
}
shinyApp(ui = ui, server = server)

每次计时器触发时,如果流式传输已开始,我们会读取so_output.txt的内容。输出:

enter image description here