★ 进度条基本实现
-
功能代码
import sys import time # 进度条-功能演示 def progress_bar_demo(title, symbol): for per in range(1, 101): print("\r", end="") print(f"【{title}】: {per}%: {symbol * (per // 2)} ", end="") sys.stdout.flush() time.sleep(0.1) print("Complete !!!") # 进度条效果演示 progress_bar_demo("Download progress", "▋")
★ 进度条应用版
-
功能代码
import sys import time # 进度条应用版 class ProgressBar: def __init__(self, title, symbol): self.title = title self.symbol = symbol # 记录生成器状态 self.is_stop = False # 获取一个进度条生成器对象 self.process = self._process() # 启动生成器 next(self.process) # 返回进度条状态 True 表示进度条已结束 def update_process(self, percent): if self.is_stop: return True # 数据校验 if percent < 0: percent = 0 elif percent > 100: percent = 100 percent = int(percent) # 更新进度条与状态 try: self.process.send(percent) except StopIteration: self.is_stop = True return False def _process(self): while True: percent = yield print("\r", end="") print(f"【{self.title}】: {percent}%: {self.symbol * (percent // 2)} ", end="") sys.stdout.flush() if percent >= 100: print("Complete !!!") break # 模拟文件总数和处理完成的文件数 total_num = 125 complete_num = 0 pb = ProgressBar("Download progress", "▋") while True: # 模拟文件处理耗时 time.sleep(0.1) complete_num += 1 is_over = pb.update_process(complete_num / total_num * 100) if is_over: break
-
运行效果