如何在R中reget Python变量?

2024-04-25 00:51:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个项目的想法在我的脑海中,我正试图使用闪亮和接口与Python。为了看看它是否可以工作,我制作了一个简单的测试应用程序:

用户界面:

# UI

library(shiny)
library(shinydashboard)

### Dashboard sidebar erstellen
sidebar <-   dashboardSidebar(

    )

body <- dashboardBody(
    fluidPage(

    # infoboxen
    valueBoxOutput("box1"),
    infoBoxOutput("box2"),

    # buttons
    actionButton("but1", "Change Value 1 to TRUE"),
    actionButton("but2", "Change Value 2 to TRUE"),
    actionButton("but3", "Change Value 1 to FALSE"),
    actionButton("but4", "Change Value 2 to FALSE")
    )  
    )


 # Hier kommt alles zusammen
shinyUi <- dashboardPage(skin = "blue",
                         dashboardHeader(title = "Python to R Test"),
                         sidebar, 
                         body
)


服务器:

# Server für Test App
library(rPython)
library(shiny)
library(shinydashboard)

shinyServer <- function(input, output) {

  # python scrip laden
  python.load("python_script.py")

  # python variable einer R variable zuweisen
  rvar1 <- python.get("blink1")
  rvar2 <- python.get("blink2")

  # Buttons
  observeEvent(input$but1, {
    python.call("func1", bool1 = TRUE)
  })

  observeEvent(input$but2, {
    python.call("func2", bool2 = TRUE)
  })

  observeEvent(input$but3, {
    python.call("func1", bool1 = FALSE)
   })

  observeEvent(input$but4, {
    python.call("func2", bool2 = FALSE)
  })

  # Infobox
  output$box1 <- renderValueBox({
      valueBox(rvar1, width = 3, icon = NULL, href = NULL, subtitle = "test", color = "green")
  })
  output$box2 <- renderInfoBox({
      infoBox(rvar2, width = 3, "Status", subtitle = "test", color = "blue")
  })
}


以及python脚本(python)_脚本.py)地址:

#!/usr/bin/python

# Script das eine Variable blinkt / Zweck: integration mir R

blink1 = 0
blink2 = 0

def func1(bool1):
    if bool1 == True:
        blink1 = 1
        print blink1
    else:
        blink1 = 0
        print blink1
    return blink1

def func2(bool2):
    if bool2 == True:
        blink2 = 1
        print blink2
    else:
        blink2 = 0
        print blink2
    return blink2

我的问题是R变量rvar1&rvar2不会从0更新为1。如何从Python脚本中将这些变量更新为相应的blink1和blink2值?甚至可以使用rPython包吗?如果没有,对如何做到这一点有什么建议吗?你知道吗

谢谢你!你知道吗


Tags: tofalsetrueinputvaluelibrarycallchange
1条回答
网友
1楼 · 发布于 2024-04-25 00:51:32

在Python中仍然需要return,只需将python.call()分配给rvar

# Buttons
observeEvent(input$but1, {
   rvar1 <- python.call("func1", TRUE)
})

observeEvent(input$but2, {
   rvar2 <- python.call("func2", TRUE)
})

observeEvent(input$but3, {
   rvar1 <- python.call("func1", FALSE)
})

observeEvent(input$but4, {
   rvar2 <- python.call("func2", FALSE)
})
...

相关问题 更多 >