R中并行计算的stdout和stderr
我正在使用包R中并行计算的stdout和stderr,r,parallel-processing,stdout,stderr,R,Parallel Processing,Stdout,Stderr,我正在使用包并行进行计算。以下是一个玩具示例: library(parallel) m = matrix(c(1,1,1,1,0.2,0.2,0.2,0.2), nrow=2) myFun = function(x) { if (any(x<0.5)) { write("less than 0.5", stderr()) return(NA) } else { write("good", stdout()) return(mean(x)) } }
并行
进行计算。以下是一个玩具示例:
library(parallel)
m = matrix(c(1,1,1,1,0.2,0.2,0.2,0.2), nrow=2)
myFun = function(x) {
if (any(x<0.5)) {
write("less than 0.5", stderr())
return(NA)
} else {
write("good", stdout())
return(mean(x))
}
}
cl = makeCluster(2, outfile="/tmp/output")
parApply(cl, m, 2, myFun)
stopCluster(cl)
有没有办法分别为stdout和stderr设置两个单独的文件?以及如何忽略“starting worker pid=…”的前两行?并行包不直接支持将stdout和stderr发送到单独的文件,但您可以自己完成:
cl = makeCluster(2)
setup = function(outfile, errfile) {
assign("outcon", file(outfile, open="a"), pos=.GlobalEnv)
assign("errcon", file(errfile, open="a"), pos=.GlobalEnv)
sink(outcon)
sink(errcon, type="message")
}
shutdown = function() {
sink(NULL)
sink(NULL, type="message")
close(outcon)
close(errcon)
rm(outcon, errcon, pos=.GlobalEnv)
}
clusterCall(cl, setup, "/tmp/output", "/tmp/errmsg")
parApply(cl, m, 2, myFun)
clusterCall(cl, shutdown)
由于在调用setup
之前发出“starting worker”消息,因此这些消息被重定向到“/dev/null”,这是未指定outfile
时的默认行为
cl = makeCluster(2)
setup = function(outfile, errfile) {
assign("outcon", file(outfile, open="a"), pos=.GlobalEnv)
assign("errcon", file(errfile, open="a"), pos=.GlobalEnv)
sink(outcon)
sink(errcon, type="message")
}
shutdown = function() {
sink(NULL)
sink(NULL, type="message")
close(outcon)
close(errcon)
rm(outcon, errcon, pos=.GlobalEnv)
}
clusterCall(cl, setup, "/tmp/output", "/tmp/errmsg")
parApply(cl, m, 2, myFun)
clusterCall(cl, shutdown)