您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Linux下怎么实现打印进度条
在Linux环境下开发时,经常需要实现进度条功能来直观展示耗时操作的执行进度。本文将详细介绍5种实现方法,涵盖Bash脚本、Python、C语言等不同技术栈。
## 一、Bash脚本实现
### 1. 基础版本
```bash
#!/bin/bash
for i in {1..100}; do
printf "\r[%-100s] %d%%" $(printf "#%.0s" $(seq 1 $i)) $i
sleep 0.1
done
echo
原理分析:
- \r
回车符使光标回到行首
- %-100s
左对齐100字符宽度的字符串
- seq
生成序列控制进度填充
#!/bin/bash
GREEN='\033[0;32m'
NC='\033[0m'
for i in {1..100}; do
printf "\r${GREEN}[%-100s]${NC} %d%%" $(printf "▓%.0s" $(seq 1 $i)) $i
sleep 0.05
done
echo
import sys
import time
def progress_bar(width=50):
for i in range(width+1):
percent = i * 100 // width
bar = '[' + '=' * i + ' ' * (width - i) + ']'
sys.stdout.write(f"\r{bar} {percent}%")
sys.stdout.flush()
time.sleep(0.1)
print()
progress_bar()
from tqdm import tqdm
import time
for i in tqdm(range(100), desc="Processing"):
time.sleep(0.05)
优势: - 自动计算ETA - 支持多线程 - 内置多种样式
#include <stdio.h>
#include <unistd.h>
void progress_bar(int progress, int total) {
float percent = (float)progress / total * 100;
int bar_width = 50;
int pos = bar_width * progress / total;
printf("\r[");
for (int i = 0; i < bar_width; ++i) {
if (i < pos) printf("=");
else printf(" ");
}
printf("] %d%%", (int)percent);
fflush(stdout);
}
int main() {
for (int i = 0; i <= 100; ++i) {
progress_bar(i, 100);
usleep(100000);
}
printf("\n");
return 0;
}
关键点:
- fflush(stdout)
强制刷新输出缓冲区
- usleep
微秒级延迟
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
def worker(n):
for _ in tqdm(range(n), desc=f"Task {n}"):
time.sleep(0.1)
with ThreadPoolExecutor() as executor:
executor.map(worker, [50, 100, 150])
#!/bin/bash
# 需要安装whiptail
{
for i in {1..100}; do
sleep 0.1
echo $i
done
} | whiptail --gauge "Processing..." 6 60 0
性能考虑:
用户体验:
跨平台兼容:
换行问题:
\r
而非\n
终端检测:
if [ -t 1 ]; then
# 交互式终端代码
else
# 非交互式处理
fi
进度计算:
本文介绍了从简单到复杂的多种进度条实现方案。实际开发中推荐: - 脚本任务:使用Bash基础版 - Python项目:首选tqdm库 - 系统编程:C语言实现
每种方案各有优劣,开发者应根据具体场景选择最合适的实现方式。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。