-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogress_bar.py
More file actions
103 lines (83 loc) · 2.85 KB
/
Copy pathprogress_bar.py
File metadata and controls
103 lines (83 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
进度条工具 - 马总专用
提供任务预估时间 + 实时进度条
"""
import sys
import time
class ProgressBar:
"""进度条类"""
def __init__(self, total_steps, task_name="任务", estimate_per_step=5):
self.total_steps = total_steps
self.task_name = task_name
self.current_step = 0
self.estimate_per_step = estimate_per_step # 每步预估秒数
self.start_time = time.time()
self.bar_length = 30
def get_elapsed(self):
return time.time() - self.start_time
def get_eta(self):
if self.current_step == 0:
return self.total_steps * self.estimate_per_step
elapsed = self.get_elapsed()
rate = elapsed / self.current_step
remaining = self.total_steps - self.current_step
return int(rate * remaining)
def format_time(self, seconds):
if seconds < 60:
return f"{seconds}秒"
elif seconds < 3600:
m = seconds // 60
s = seconds % 60
return f"{m}分{s}秒"
else:
h = seconds // 3600
m = (seconds % 3600) // 60
return f"{h}小时{m}分"
def show(self, current_item=""):
"""显示进度条"""
self.current_step += 1
progress = self.current_step / self.total_steps
filled = int(self.bar_length * progress)
bar = '=' * filled + '-' * (self.bar_length - filled)
percent = int(progress * 100)
elapsed = self.get_elapsed()
eta = self.get_eta()
# 状态符号
if self.current_step == self.total_steps:
status = "[OK]"
elif self.current_step < self.total_steps * 0.3:
status = "[>>]"
elif self.current_step < self.total_steps * 0.7:
status = "[>>]"
else:
status = "[>>]"
# 输出
line = f"\r{status} |{bar}| {percent}% | {self.current_step}/{self.total_steps} | ETA: {self.format_time(eta)}"
if current_item:
line += f" | {current_item}"
sys.stdout.write(line)
sys.stdout.flush()
if self.current_step >= self.total_steps:
sys.stdout.write('\n')
sys.stdout.flush()
def done(self, message=""):
"""完成任务"""
elapsed = self.get_elapsed()
msg = f"\n[DONE] Time: {self.format_time(int(elapsed))}"
if message:
msg += f" | {message}"
print(msg)
def demo():
"""演示"""
print("=" * 50)
print("[PROGRESS BAR DEMO]")
print("=" * 50)
pb = ProgressBar(10, "生成图片", estimate_per_step=1)
for i in range(10):
pb.show(f"处理第{i+1}项...")
time.sleep(0.5)
pb.done()
if __name__ == "__main__":
demo()