gpt4 book ai didi

将系统控制台输出返回到用户界面

转载 作者:行者123 更新时间:2023-12-04 15:06:21 26 4
gpt4 key购买 nike

我有一个使用 shiny 和 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)

最佳答案

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

相反,当 intern = TRUE 时,R session (和 shiny)在执行命令时被阻塞。

请检查以下内容:

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)

result

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

关于将系统控制台输出返回到用户界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66012162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com