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

R语言cli包连续创建进度条仅显首个,如何无需Sys.sleep显示全部?

问题:cli进度条连续快速创建时仅显示第一个

当连续快速创建多个cli进度条时,仅第一个进度条会显示。但添加短延时Sys.sleep(0.2)后,所有进度条均可正常显示,相关代码如下:

options(cli.progress_show_after = 0)

fun <- function(step) {
  cli::cli_progress_bar(
    clear = FALSE
  )
  cli::cli_progress_update(inc = 0)
  cli::cli_progress_done()
}

fun_sleep <- function(step) {
  cli::cli_progress_bar(
    clear = FALSE
  )
  cli::cli_progress_update(inc = 0)
  cli::cli_progress_done()
  Sys.sleep(0.2)
}

purrr::walk(1:3, function(x) fun(x))

purrr::walk(1:3, function(x) fun_sleep(x))

请问如何在不使用Sys.sleep(0.2)的情况下显示全部进度条?

更新
我已在GitHub提交相关Issue


解决方法

可以通过手动刷新输出缓冲区的方式,让进度条及时显示,无需依赖Sys.sleep(),具体有两种实现方式:

  • 使用cli包内置的刷新函数
    修改fun函数,在完成进度条后调用cli::cli_flush()强制刷新输出:
fun <- function(step) {
  cli::cli_progress_bar(
    clear = FALSE
  )
  cli::cli_progress_update(inc = 0)
  cli::cli_progress_done()
  cli::cli_flush()
}
  • 使用基础R的控制台刷新函数
    也可以用flush.console()实现同样效果:
fun <- function(step) {
  cli::cli_progress_bar(
    clear = FALSE
  )
  cli::cli_progress_update(inc = 0)
  cli::cli_progress_done()
  flush.console()
}

原理说明

快速创建并销毁进度条时,R的输出缓冲区可能还没来得及将进度条内容输出到控制台,就被后续操作覆盖。手动刷新缓冲区能强制将当前输出内容立即推送到控制台,从而让所有进度条都能正常显示。


内容的提问来源于stack exchange,提问作者Giovanni Colitti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:37:14