【发布时间】:2017-07-01 14:22:57
【问题描述】:
我有这个项目的想法,我正在尝试使用 Shiny 并与 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_script.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 包吗?如果没有,关于如何做到这一点的任何建议?
谢谢!
【问题讨论】:
-
尝试在 Python 函数中添加
return行。 -
谢谢,但它不起作用。
-
真的吗?照原样,
print不会从函数返回任何值。请说明您是如何添加退货的。见here。 -
另外,您是否按下了
TRUE值闪亮按钮?此外,在python.call中删除分配并通过 T/F。 -
如果我按下 Shiny 中的按钮,我可以看到 Python 中的变量如何变化,这就是我打印的原因。删除
python.call中的分配也无济于事。