方法一:使用print()函数实现文本进度条
示例代码
import time
import sys
def print_progress_bar(iteration, total, prefix='', length=50):
percent = (iteration / total) * 100
filled_length = int(length * iteration // total)
bar = '█' * filled_length + '-' * (length - filled_length)
sys.stdout.write(f'\r{prefix} |{bar}| {percent:.2f}% Complete')
sys.stdout.flush()
# 示例用法
total_steps = 100
for i in range(total_steps + 1):
print_progress_bar(i, total_steps)
time.sleep(0.1)
print() # 换行,以便最后输出后换行
解释
print_progress_bar函数负责计算进度并打印进度条。sys.stdout.write和sys.stdout.flush用于动态更新同一行的输出。