# put this code into the file plumber.R and run:
# plumber::plumb("plumber.R")$run(port=9999)
# 1. click "Try it out"
# 2. enter a package name that you want to try
# 3. click "Execute"
#* @get /search_path
#* @param lib library to load
function(lib) {
# callr runs the anonymous function in a fresh session
rp <- callr::r_bg({
function(lib) {
library(package = lib, character.only = TRUE)
return(list(search_path = search(),
process_id = Sys.getpid(),
the_time = Sys.time()))
}
},
args = list(lib = lib))
# wait for a result with 30 seconds timeout
rp$wait(30000)
if(rp$is_alive() == TRUE) {
rp$kill()
stop("time exceeded")
}
# return the result
rp$get_result()
}
有点离题,但在这个上下文中可能也很有趣:允许并行请求可以通过future包启用。
# submit two requests for packages within less than 10 seconds of
# each other and compare the time stamps to see that they were processed
# in parallel and in different sessions
future::plan(future::multisession)
#* @get /search_path
#* @param lib library to load
function(lib) {
future::future({
# callr runs the anonymous function in a fresh session
rp <- callr::r_bg({
function(lib) {
Sys.sleep(10)
library(package = lib, character.only = TRUE)
return(list(search_path = search(),
process_id = Sys.getpid(),
the_time = Sys.time()))
}
},
args = list(lib = lib))
# wait for a result with 30 seconds timeout
rp$wait(30000)
if(rp$is_alive() == TRUE) {
rp$kill()
stop("time exceeded")
}
# return the result
rp$get_result()
}, seed = TRUE)
}
1条答案
按热度按时间ctehm74n1#
正如Konrad Rudolph的评论中所建议的那样,
callr
可以很好地完成这项工作。对不同的包多次执行1.-3.(参见代码块)将表明每次运行都是在新的R会话中执行的(参见process_id),因此搜索路径是独立的。
有点离题,但在这个上下文中可能也很有趣:允许并行请求可以通过
future
包启用。