Not able to print python code in R shiny dashboard

i am not sure what is wrong with the below code. I am not able to run the below python code

ui.R file..........................................


library(shiny)
library(shinydashboard)
library(reticulate)

ui <- dashboardPage(
    dashboardHeader(disable = TRUE),
    dashboardSidebar(disable = TRUE),
    dashboardBody(
        # Boxes need to be put in a row (or column)
        fluidRow(
            box(actionButton("upload","Upload",width = 150),
                actionButton("clear_upload","Clear",width = 150),
                verbatimTextOutput("code"))
        )
    )
)

server.R file

server <- function(input, output) {
    
    get_code <- eventReactive(input$upload,{
        py_run_string("def add(x, y):return x + (y+12)")
        py_run_string("print(add(5,1))")
    })
    
    observeEvent(input$upload, {
        output$code <- renderPrint(get_code())
        })
    
    observeEvent(input$clear_upload, {
        output$code <- renderPrint("")
        })
}

There are a few things to do to get this working properly.

  1. It is bad practice to nest render statements inside observe events. You open yourself up to potential problems once your app gets larger. To remedy that, I split out the renderText statement (previously renderPrint) and switched to a reactiveValue container to capture your python return instead of an eventReactive. So now you have two observeEvents that define your reactiveValue. You can probably convert back to eventReactive, although this way always made more sense to me.
  2. To access your python return value, you need to access the main module using the 'py$' syntax. (https://rstudio.github.io/reticulate/articles/calling_python.html#executing-code) Also, since the python function is static we can move that outside of the server function.

Here is a functioning version with the changes stated above. Converted to app.R style to make it easier to copy and paste here:

library(shiny)
library(shinydashboard)
library(reticulate)

#Global Py function
py_run_string("def add(x, y):return x + (y+12)")

ui <- dashboardPage(
  dashboardHeader(disable = TRUE),
  dashboardSidebar(disable = TRUE),
  dashboardBody(
    # Boxes need to be put in a row (or column)
    fluidRow(
      box(actionButton("upload","Upload",width = 150),
          actionButton("clear_upload","Clear",width = 150),
          verbatimTextOutput("code"))
    )
  )
)

server <- function(input, output) {
  
  get_code <- reactiveValues(text = "")
  
  observeEvent(input$upload,{
    get_code$text <- py$add(5,1)
  })
  
  observeEvent(input$clear_upload, {
    get_code$text <- ""
  })
  
  output$code <- renderText({
    get_code$text
  })
}

shinyApp(ui,server)
2 Likes

Thanks. and perfect..............

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.