首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 級聯進度條:StepedProgress 多層任務進度顯示

     編輯:更多程式設計知識

多層任務 (如:下載 60% -> 解壓 40%,解壓內又有子任務) 需要將子任務進度按權重折算至總進度。StepedProgress 類別實現樹狀進度聚合,支援動態子任務分割與即時顯示。

核心類別


class StepedProgress:
    def __init__(self, stockPercent=[1], parentProgress=None):
        self.percent = 0
        self.info = ''
        self.subProgress = []
        self.cur_running_process = 0
        self.stockPercent = [p/sum(stockPercent) for p in stockPercent]  # 正規化
        self.parentProgress = parentProgress
        if len(self.stockPercent) > 1:
            for p in self.stockPercent:
                self.subProgress.append(StepedProgress(parentProgress=self))

    def subprogress(self, index):
        if index >= len(self.subProgress):
            return self.subProgress[-1]
        if index < self.cur_running_process:
            return self.subProgress[self.cur_running_process]
        self.cur_running_process = index
        return self.subProgress[index]

    def notifyParentProgress(self, percent, info=None):
        # 將子進度折算至父層
        total = sum(self.stockPercent[:self.cur_running_process])
        total += percent/100.0 * self.stockPercent[self.cur_running_process]
        self.notifyProgress(total*100, info)

    def notifyProgress(self, percent, info=None):
        if percent > self.percent:
            self.percent = percent
        if info:
            self.info = info
        if self.parentProgress:
            self.parentProgress.notifyParentProgress(percent, info)
        else:
            print(f"{self.info[:77].ljust(80,'.')} [{self.percent:.1f}%]")

使用範例


s = StepedProgress([60, 40])          # 總權重 60:40
s.notifyProgress(10, 'aaa')           # 總進度 10%

s1 = s.subprogress(0)                 # 子任務 0 (佔 60%)
s1.notifyProgress(50, 'bbb')          # 總進度 10 + 50*0.6 = 40%

s3 = s.subprogress(1)                 # 子任務 1 (佔 40%)
s3 = StepedProgress([1, 1], parentProgress=s3.parentProgress)  # 再分兩子任務
s3.notifyProgress(20, 'ddd')          # 總進度 60 + 20*0.4*0.5 = 64%

s4 = s3.subprogress(0)
s4.notifyProgress(50, 'eee')          # 總進度 60 + 50*0.4*0.5 = 70%
s5 = s3.subprogress(1)
s5.notifyProgress(50, 'fff')          # 總進度 60 + 100*0.4*0.5 = 90%

輸出


aaa............................................................................. [10.0%]
bbb............................................................................. [40.0%]
ddd............................................................................. [64.0%]
eee............................................................................. [70.0%]
fff............................................................................. [90.0%]

設計亮點

  • 權重正規化:輸入任意正數自動轉比例。
  • 樹狀結構:任意層級嵌套,自動向根聚合。
  • 動態分割:subprogress 可重新建立子任務權重。
  • 單調遞增:進度不回退,避免視覺跳動。

適合建置腳本、資料處理管線、多階段部署等長流程進度視覺化。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved