本文目录导读:

Bash/Shell 脚本进度条
简单进度条示例
#!/bin/bash
# 显示进度条函数
show_progress() {
local current=$1
local total=$2
local width=50
local percentage=$((current * 100 / total))
local filled=$((current * width / total))
local empty=$((width - filled))
printf "\r["
printf "%${filled}s" | tr ' ' '='
printf "%${empty}s" | tr ' ' ' '
printf "] %d%%" "$percentage"
}
# 模拟进度
total=100
for ((i=1; i<=total; i++)); do
show_progress $i $total
sleep 0.05 # 模拟耗时操作
done
echo ""
echo "完成!"
带颜色的美化版本
#!/bin/bash
show_progress_bar() {
local current=$1
local total=$2
local width=40
local percentage=$((current * 100 / total))
local filled=$((current * width / total))
local empty=$((width - filled))
printf "\r\033[32m["
printf "%${filled}s" | tr ' ' '█'
printf "%${empty}s" | tr ' ' '░'
printf "]\033[0m %d%%" "$percentage"
}
# 使用示例
for i in {1..20}; do
show_progress_bar $i 20
sleep 0.1
done
echo ""
Python 脚本进度条
标准库版本(无需安装)
import sys
import time
def progress_bar(current, total, width=50):
"""显示进度条"""
percent = current / total * 100
filled = int(width * current // total)
bar = '█' * filled + '░' * (width - filled)
sys.stdout.write(f'\r进度: |{bar}| {percent:.1f}% ({current}/{total})')
sys.stdout.flush()
# 使用示例
total = 100
for i in range(total + 1):
progress_bar(i, total)
time.sleep(0.02) # 模拟耗时操作
print("\n完成!")
使用 tqdm 库(推荐)
from tqdm import tqdm
import time
# 简单用法
for i in tqdm(range(100), desc="处理中"):
time.sleep(0.02)
# 高级用法
items = ["任务1", "任务2", "任务3", "任务4", "任务5"]
with tqdm(total=len(items), desc="批量处理", bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]') as pbar:
for item in items:
# 执行任务
time.sleep(0.5)
pbar.set_postfix({"当前任务": item})
pbar.update(1)
结合真实任务的文件复制进度条
import os
import sys
import shutil
def copy_with_progress(src, dst):
"""显示文件复制进度的函数"""
source_size = os.path.getsize(src)
copied = 0
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
while True:
chunk = fsrc.read(1024 * 1024) # 1MB 块
if not chunk:
break
fdst.write(chunk)
copied += len(chunk)
percent = copied / source_size * 100
sys.stdout.write(f'\r复制: {percent:.1f}% | {copied/1024/1024:.1f}MB / {source_size/1024/1024:.1f}MB')
sys.stdout.flush()
print("\n复制完成!")
# 使用方法
# copy_with_progress("source_file.bin", "destination_file.bin")
多个任务的复合进度条
import time
from tqdm import tqdm
def complex_progress_demo():
"""多任务复合进度条"""
# 嵌套进度条
outer_task = tqdm(range(5), desc="外部任务", position=0)
inner_task = tqdm(range(10), desc="内部任务", position=1)
for i in outer_task:
for j in inner_task:
time.sleep(0.05)
inner_task.update(1)
inner_task.reset()
# 更新外部进度条描述
outer_task.set_description(f"处理第 {i+1} 步")
outer_task.close()
inner_task.close()
# 运行演示
complex_progress_demo()
安装 tqdm(推荐)
# pip 安装 pip install tqdm # 或者使用 conda conda install tqdm
自定义进度条类
class ProgressBar:
"""可复用的进度条类"""
def __init__(self, total, width=50, label="进度"):
self.total = total
self.width = width
self.label = label
self.current = 0
def update(self, step=1):
self.current += step
self.display()
def display(self):
percent = self.current / self.total * 100
filled = int(self.width * self.current // self.total)
bar = '█' * filled + '░' * (self.width - filled)
sys.stdout.write(f'\r{self.label}: |{bar}| {percent:.1f}%')
sys.stdout.flush()
def finish(self):
print("\n完成!")
# 使用示例
progress = ProgressBar(100, label="下载")
for i in range(100):
time.sleep(0.05)
progress.update()
progress.finish()
使用建议
- 安装 tqdm:对于 Python 项目,推荐使用
tqdm,它功能强大且易于使用 - 进度条刷新频率:不要刷新太频繁,影响性能
- 处理异常情况:确保在异常时能清除进度条
- 描述信息:添加有意义的描述信息,让用户知道当前在做什么
您可以根据具体需求选择合适的方法,如果需要更特定的功能,请告诉我具体场景。