打印进度条
文章目录
- 1.Python语言实现
- (1)黑白色
- (2)彩色:蓝色
- 2.C++语言实现
- (1)黑白颜色
- (2)彩色版:红绿色
1.Python语言实现
(1)黑白色
import sys
import timedef progress_bar(percentage, width=50):"""打印进度条:param percentage: 当前进度百分比 (0-100):param width: 进度条的宽度,默认是50字符"""completed = int(width * (percentage / 100)) #已完成部分remaining = width - completed #未完成部分bar = f"[{'#' * completed}{'.' * remaining}]"sys.stdout.write(f"\rProgress: {percentage:3d}% {bar}") #动态刷新行sys.stdout.flush() #※实现动态更新,不换行输出# 模拟进度条运行
for i in range(101): #0%到100%progress_bar(i) #更新进度条time.sleep(0.05) #模拟延迟print("\nDone!") #结束后换行
(2)彩色:蓝色
import sys
import timedef progress_bar(percentage, width=50):"""打印进度条:param percentage: 当前进度百分比 (0-100):param width: 进度条的宽度,默认是50字符"""completed = int(width * (percentage / 100)) # 已完成部分remaining = width - completed # 未完成部分# 进度条的蓝色部分blue = "\033[34m"reset = "\033[0m"bar = f"[{blue}{'#' * completed}{reset}{'.' * remaining}]"sys.stdout.write(f"\rProgress: {percentage:3d}% {bar}") # 动态刷新行sys.stdout.flush() # ※实现动态更新,不换行输出# 模拟进度条运行
for i in range(101): # 0%到100%progress_bar(i) # 更新进度条time.sleep(0.05) # 模拟延迟print("\nDone!") # 结束后换行
2.C++语言实现
(1)黑白颜色
#include <iostream>
#include <thread> //用于 sleep_for
#include <chrono> //用于时间延迟
using std::cout;
using std::endl;void progressBar(int percentage, int width = 50) {int completed = (percentage * width) / 100; //已完成部分的宽度int remaining = width - completed; //未完成部分的宽度cout << "\rProgress: ["; // \r 回到行首,覆盖之前的内容for (int i = 0; i < completed; ++i) {cout << "#"; // 已完成部分}for (int i = 0; i < remaining; ++i) {cout << "."; // 未完成部分}cout << "] " << percentage << "%"; // 输出百分比cout.flush(); // 刷新输出流
}int main() {for (int i = 0; i <= 100; ++i) { // 模拟进度从0%到100%progressBar(i); // 更新进度条std::this_thread::sleep_for(std::chrono::milliseconds(50)); // 模拟延迟}cout << endl << "Done!" << endl; // 进度完成后换行return 0;
}
(2)彩色版:红绿色
#include <iostream>
#include <thread> //用于 sleep_for
#include <chrono> //用于时间延迟
using std::cout;
using std::endl;void progressBar(int percentage, int width = 50) {int completed = (percentage * width) / 100; //已完成部分的宽度int remaining = width - completed; //未完成部分的宽度cout << "\rProgress: ["; // \r 回到行首,覆盖之前的内容// 已完成部分,使用绿色cout << "\033[32m";for (int i = 0; i < completed; ++i) {cout << "#"; // 已完成部分}// 未完成部分,使用红色cout << "\033[31m";for (int i = 0; i < remaining; ++i) {cout << "."; // 未完成部分}// 重置颜色并输出百分比cout << "\033[0m] " << percentage << "%"; // 输出百分比cout.flush(); // 刷新输出流
}int main() {for (int i = 0; i <= 100; ++i) { // 模拟进度从0%到100%progressBar(i); // 更新进度条std::this_thread::sleep_for(std::chrono::milliseconds(50)); // 模拟延迟}cout << endl << "Done!" << endl; // 进度完成后换行return 0;
}