You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在future()中使用本地golem包?基于golem与brochure构建的Shiny应用引用非系统库本地包函数问题

解决Shiny + Future中调用本地未安装包的问题

我明白你遇到的麻烦了——在Shiny(用golem+brochure架构)里用future异步调用本地开发包时,新启动的R进程找不到你的humblFinance包,因为它不在系统默认的win-library路径里。结合你的场景,给你几个可行的解决方案:

核心原因

Future会启动独立的R进程,这个进程默认只加载系统库中的包,不会自动识别你项目里的本地开发包路径,所以才会报“找不到包”的错误。另外要特别注意:Shiny的input对象不能直接在future进程里访问,得提前把需要的参数提取出来,不然异步进程会丢失Shiny的上下文。

解决方案1:直接加载本地包源码(推荐)

用devtools::load_all()可以直接加载本地包的源码,不需要安装到系统库。你需要在future进程里显式执行这个操作,同时提前提取input参数:

# 在Shiny app的启动入口(比如golem的app_server.R或者brochure的页面定义前)
# 先让主进程也加载本地包,确保逻辑一致
local_pkg_dir <- "./path/to/humblFinance" # 替换成你的本地包实际路径(相对/绝对路径都可)
devtools::load_all(local_pkg_dir)

# 修改你的renderPlot代码
output$p1 <- renderPlot({ 
  # 提前提取需要的input值,避免在future里直接访问input
  selected_ticker <- input$tickerInput
  
  future::future({ 
    # 在future进程中重新加载本地包
    devtools::load_all(local_pkg_dir)
    
    # 现在可以正常调用包函数了
    out <- humblFinance::collect_price(symbol = selected_ticker, range = "1m") 
    
    out %>% ggplot2::ggplot(ggplot2::aes(x = date, y = fclose)) + 
      ggplot2::geom_line(size = 1) + 
      ggplot2::labs(title = glue::glue("{selected_ticker} Price Chart"), 
                    y = "Closing Price", x = "") 
  }) %...>% ( 
    function(result){ result } 
  ) %...!% ( 
    function(error){ warning("生成图表失败:", error) } 
  ) 
})

解决方案2:把本地包路径加入future的库路径

如果不想用devtools,也可以把本地包的所在目录(注意是包的上层目录,或者包编译后的安装目录)加入future进程的.libPaths():

output$p1 <- renderPlot({ 
  selected_ticker <- input$tickerInput
  local_pkg_path <- "./path/to/your/package/directory" # 比如包在项目根目录的packages文件夹下,就写"./packages"
  
  future::future({ 
    # 将本地包路径添加到当前进程的库路径
    .libPaths(c(local_pkg_path, .libPaths()))
    
    # 加载包
    library(humblFinance, character.only = TRUE)
    
    out <- collect_price(symbol = selected_ticker, range = "1m") 
    # 后续绘图逻辑不变
    out %>% ggplot2::ggplot(ggplot2::aes(x = date, y = fclose)) + 
      ggplot2::geom_line(size = 1) + 
      ggplot2::labs(title = glue::glue("{selected_ticker} Price Chart"), 
                    y = "Closing Price", x = "") 
  }) %...>% ( 
    function(result){ result } 
  ) %...!% ( 
    function(error){ warning("生成图表失败:", error) } 
  ) 
})

额外注意事项

  1. 路径要准确:确保你指定的本地包路径是正确的,相对路径是相对于Shiny app的工作目录(golem项目一般是项目根目录)。
  2. 避免重复安装:不要在future里用remotes::install_local(),每次运行都安装会拖慢速度,而且完全没必要——直接加载源码或添加库路径就够了。
  3. Future计划设置:Windows下默认用multisession计划,每个future进程都是独立的,所以每次都要重新设置路径/加载包;如果是Linux/macOS可以用multicore,会继承主进程的库路径,但Windows不支持这个选项。

内容的提问来源于stack exchange,提问作者JJ Fantini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 14:49:05