【问题标题】:Return system console output to user interface将系统控制台输出返回到用户界面
【发布时间】:2021-02-04 05:56:19
【问题描述】:

我有一个使用闪亮和system 运行的bash 脚本。运行需要很长时间,所以我想向用户提供有关进度的反馈。在 bash 脚本中,我有定期更新用户的消息,我正在尝试找到一种方法将它们打印在 UI 中。

这是一个最小的工作示例,我希望在控制台中显示“输出 1”和“输出 2”时将它们返回给用户。

非常感谢任何帮助。

library(shiny)

ui <- fluidPage(
  actionButton("run", "Print to Console")
)

server <- function(input, output, session) {
  observeEvent(input$run,{
    system(c("echo output 1; sleep 2; echo output 2"))
  })
}

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我建议异步运行system 命令并将输出重定向到日志文件。同时,您可以通过reactiveFileReader 连续读取日志文件。

    相比之下,当intern = TRUE 执行命令时,R 会话(和闪亮)被阻塞。

    请检查以下内容:

    library(shiny)
    
    file.create("commands.sh", "output.log")
    Sys.chmod("commands.sh", mode = "0777", use_umask = TRUE)
    writeLines(c("#!/bin/bash", "echo output 1","sleep 2", "echo output 2"), con = "commands.sh")
    
    ui <- fluidPage(
      actionButton("run_intern", "Run intern"),
      textOutput("myInternTextOutput"),
      hr(),
      actionButton("run_extern", "Run extern"),
      textOutput("myExternTextOutput")
    )
    
    server <- function(input, output, session) {
      systemOutputIntern <- eventReactive(input$run_intern,{
        system(command = "echo output 1; sleep 2; echo output 2", intern = TRUE)
      })
      
      output$myInternTextOutput <- renderText(systemOutputIntern())
      
      observeEvent(input$run_extern,{
        system(command = "./commands.sh 2>&1 | tee output.log", intern = FALSE, wait = FALSE)
      })
      
      log <- reactiveFileReader(200, session, filePath = "output.log", readLines)
      output$myExternTextOutput <- renderText(log())
    }
    
    shinyApp(ui, server)
    

    PS:作为替代方案,您可能需要检查库中的AsyncProgress(ipc)。

    【讨论】:

    • 如果你异步执行外部命令,即通过pipe,则无需通过文件走弯路。
    • 那么,如何将输出转换为闪亮的响应式?
    • @ismirsehregal 感谢您的建议。我现在唯一的问题是输出会同时出现在 UI 中,而不是连续出现,因此用户仍然想知道进度是什么。就像我们设置sleep 100 一样,那将不是很有用。有什么想法吗?
    • @StephenWilliams 我刚刚在 Ubuntu 上进行了测试,你是对的。直接使用system 运行命令时,它没有按预期工作(我不知道为什么)。但是,在将命令包装在单独的脚本中后,它确实可以工作。请查看我的编辑。
    • @ismirsehregal 这非常有效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    相关资源
    最近更新 更多