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

如何封装不可修改的含while循环的Python函数 接入tqdm实现进度条

解决方案

因为无法修改原函数内部逻辑,无法直接获取循环实时进度,所有方案都基于你对原函数的先验知识(比如已知总运行时长、总迭代次数),或者使用不确定进度的动画样式。

方案1:已知原函数总运行时长/总迭代量,实现精准进度条

用多线程实现,子线程运行原函数,主线程同步更新tqdm进度,完全不修改原函数代码。

import threading
from tqdm import tqdm
import time

# 原函数完全不修改
def myfunc():
    i = 0
    while i < 5 * 1000:
        i += 1
        time.sleep(0.001)
    return i

def myfunc_with_progress():
    # 已知myfunc总迭代量为5000,总运行时长约为5秒
    total = 5000
    res = None
    def run_func():
        nonlocal res
        res = myfunc()
    
    # 启动子线程运行原函数
    func_thread = threading.Thread(target=run_func, daemon=True)
    func_thread.start()

    # 主线程更新进度条
    with tqdm(total=total) as pbar:
        for _ in range(total):
            if not func_thread.is_alive():
                # 函数提前跑完的话直接把进度条拉满
                pbar.update(total - pbar.n)
                break
            pbar.update(1)
            time.sleep(0.001) # 和原函数单步耗时对齐
    # 等待线程结束,返回原函数结果
    func_thread.join()
    return res

# 调用方式和原函数完全一致
result = myfunc_with_progress()
print(result)

如果原函数运行时长有波动,也可以按总时长控制进度条更新,比如已知总时长约5秒,将total设为100,每0.05秒更新1步,可降低误差。该方案返回值、异常表现和原函数完全一致,仅增加了进度条展示逻辑。

方案2:未知原函数运行信息,使用不确定进度条

如果完全不知道原函数的运行时长,可以用tqdm的不确定进度模式,展示加载动画直到函数运行结束。

import threading
from tqdm import tqdm
import time

def myfunc_with_unknown_progress():
    res = None
    def run_func():
        nonlocal res
        res = myfunc()
    
    func_thread = threading.Thread(target=run_func, daemon=True)
    func_thread.start()

    # 不确定总长度的进度条,会展示循环动画
    with tqdm(bar_format='{l_bar}{bar}| 运行中...', unit=' 帧') as pbar:
        while func_thread.is_alive():
            pbar.update(1)
            time.sleep(0.1)
    
    func_thread.join()
    return res

内容的提问来源于stack exchange,提问作者adam.hendry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 21:18:03