最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - How to run on.exit if user abortsinterrupts the calculation? - Stack Overflow

programmeradmin0浏览0评论

Question: In R or RStudio, if a user aborts an ongoing calculation (by clicking the stop sign or pressing esc), on.exit is not called. Is there a way such that if the user presses esc, a certain statement runs first before aborting the calculation?

Example:

testf <- function() {Sys.sleep(3); on.exit(cat("on.exit output"))}
testf()

When pressing esc, no output is printed.

Real world example: I am using cl <- parallel::makePSOCKcluster(2) within a function to use parLapply. When the user aborts the calculation, I want to call stopCluster(cl). I am on a MacBook m3, but this needs to work on Windows as well.

Question: In R or RStudio, if a user aborts an ongoing calculation (by clicking the stop sign or pressing esc), on.exit is not called. Is there a way such that if the user presses esc, a certain statement runs first before aborting the calculation?

Example:

testf <- function() {Sys.sleep(3); on.exit(cat("on.exit output"))}
testf()

When pressing esc, no output is printed.

Real world example: I am using cl <- parallel::makePSOCKcluster(2) within a function to use parLapply. When the user aborts the calculation, I want to call stopCluster(cl). I am on a MacBook m3, but this needs to work on Windows as well.

Share Improve this question edited Feb 7 at 18:17 jay.sf 73k8 gold badges63 silver badges125 bronze badges asked Feb 7 at 15:48 SaidSaid 334 bronze badges 2
  • 2 Obviously, you need to define on.exit() before the calculation that will be interrupted, otherwise the line will not be interpreted. – jay.sf Commented Feb 7 at 17:37
  • 1 For some reason, cl didn't close when I tried it. But I tried again with a fresh mind and code, moved the on.exit all the way up, and it works! Thanks! – Said Commented 2 days ago
Add a comment  | 

1 Answer 1

Reset to default 2

In your function par_fun, make cluster and define on.exit in subsequent lines.

> par_fun <- \(ncpu=2L) {
+   cl <- parallel::makePSOCKcluster(ncpu)
+   on.exit(parallel::stopCluster(cl))
+   parallel::parLapply(cl, seq_len(3), inner_fun)
+ }
> par_fun()  ## normal run
[[1]]
[1] "Done."

[[2]]
[1] "Done."

[[3]]
[1] "Done."

> showConnections()
     description class mode text isopen can read can write
> par_fun()  ## interrupted
> showConnections()
     description class mode text isopen can read can write

Data:

inner_fun <- \(i) {Sys.sleep(1); return('Done.')}
发布评论

评论列表(0)

  1. 暂无评论