从并行功能(并行或未来框架)内发送消息

问题描述 投票:0回答:2

我想在并行过程中使用

parallel
包或未来框架和
pblapply::pblapply()
将消息从函数内发送到 R 控制台。

这是一个不向 R 控制台发送任何消息的 reprex:

# library
library(pbapply)
library(stringi)
library(parallel)

# make fun
fun_func <- function(x){
  cat(paste0("hello world ",x))
  return(paste0("hello world ",x))}


# get data
set.seed(23)
d <- stri_rand_strings(100, 2, '[a-z]')
names(d) <- d

# make cluster
cl <- parallel::makeCluster(3)

# load func
clusterExport(cl, c("fun_func"))

# run function
pblapply(cl=cl,X=d,FUN=fun_func) -> res

# stop cluster
parallel::stopCluster(cl)

# show res
head(res)
#> $of
#> [1] "hello world of"
#> 
#> $is
#> [1] "hello world is"
#> 
#> $vl
#> [1] "hello world vl"
#> 
#> $zz
#> [1] "hello world zz"
#> 
#> $vz
#> [1] "hello world vz"
#> 
#> $ws
#> [1] "hello world ws"

创建于 2022-12-07,使用 reprex v2.0.2

更新: 我刚刚了解到,在 Windows/RStudio 中获取控制台消息可能很难。但是,使用 ParallelLogger

 记录消息可能是一种选择。
不幸的是我无法实现它。
因此,我很高兴有一个将消息发送到控制台或文件的解决方案。

r parallel-processing
2个回答
0
投票
future

框架之上使用并行化方法,例如future_lapplyfurrrforeachdoFuture,很快还有 pbapply (https://github.com/psolymos/pbapply/issues/54),来自 cat()

print() 的输出并行工作线程中的 
message()
warning()
等会在并行任务完成时在主 R 会话中被捕获并真正重新输出(“中继”)。您可以在
https://future.futureverse.org/articles/future-2-output.html
. 中阅读相关内容 如果您想查看

near-live

输出,即并行任务仍在运行时生成的输出,那么您可以使用 progressr 包。它旨在在使用 Futureverse 时发送近乎实时的进度更新。这些更新还可以包括自定义消息。有关示例,请参阅 https://progressr.futureverse.org/#parallel-processing-and-progress-updates


0
投票

message_parallel <- function(...){ system(sprintf('echo "\n%s\n"', paste0(..., collapse=""))) }

感谢 Anatoly Vasilyev 创建了这个简单的答案,该答案确实与 mclapply 和 pbmclapply 配合得很好。
原帖:
在 R Studio 中从 mclapply 打印

© www.soinside.com 2019 - 2024. All rights reserved.