我正在尝试在R Shiny中进行并行处理,我想做的并行任务是调用python脚本。但是,它不起作用,也无法将结果从python取回R。 以下是示例R Shiny和Python代码。 App.R
library(shiny)
library(reticulate)
library(doParallel)
library(foreach)
ui <- fluidPage(
# Application title
titlePanel("Sample Program"),
mainPanel(
uiOutput("txtValue")
)
)
server <- function(input, output) {
source_python("../../PythonCode/Multiprocessing/multip.py")
cl <- makeCluster(detectCores(), type='PSOCK')
registerDoParallel(cl)
result <- foreach(i=1:5) %dopar% fsq(i)
stopCluster(cl)
output$txtValue <- renderUI({
result
})
}
shinyApp(ui = ui, server = server)
Python代码(multip.py)
def fsq(x):
return x**2
答案 0 :(得分:2)
错误消息独立于shiny
:
library(reticulate)
library(doParallel)
library(foreach)
library(parallel)
source_python("multip.py")
cl <- makeCluster(detectCores(), type = 'PSOCK')
registerDoParallel(cl)
# throws: Error in unserialize(socklist[[n]]) : error reading from connection
foreach(i = 1:5) %dopar% fsq(i)
stopCluster(cl)
我这样解释,使得人们不能序列化Python函数,因为可以序列化R函数。一个简单的解决方法是在循环中使用source_python
:
library(doParallel)
library(foreach)
library(parallel)
cl <- makeCluster(detectCores(), type = 'PSOCK')
registerDoParallel(cl)
foreach(i = 1:5) %dopar% {
reticulate::source_python("multip.py")
fsq(i)
}
stopCluster(cl)