多層任務 (如:下載 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 可重新建立子任務權重。適合建置腳本、資料處理管線、多階段部署等長流程進度視覺化。