在Python中,有多种方式可以实现进度条。这里,我将介绍七种常见的方法:使用tqdm
(这是一个外部库,非常流行且易于使用)、rich、click、progressbar2等库以及纯Python的print
函数与time
库来模拟进度条。
目录
tqdm
库首先,你需要安装tqdm
库。你可以使用pip来安装:
pip install tqdm
然后,你可以使用以下代码来显示进度条:
- from tqdm import tqdm
- import time
-
- # 模拟一个需要花费时间的任务
- for i in tqdm(range(100)):
- time.sleep(0.01) # 假设每个迭代需要0.01秒
在这个例子中,tqdm
会自动处理进度条的显示,你不需要做其他任何事情。每次迭代时,进度条都会更新。
效果:
10%|█ | 10/100 [00:01<00:09, 9.98it/s]
如果你不想使用外部库,你也可以使用Python的print
函数和time
库来模拟一个简单的进度条。但是请注意,这种方法没有tqdm
那么灵活和强大。
以下是一个简单的例子:
- import time
- import sys
-
- def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd="\r"):
- """
- Call in a loop to create terminal progress bar
- @params:
- iteration - Required : current iteration (Int)
- total - Required : total iterations (Int)
- prefix - Optional : prefix string (Str)
- suffix - Optional : suffix string (Str)
- decimals - Optional : positive number of decimals in percent complete (Int)
- length - Optional : character length of bar (Int)
- fill - Optional : bar fill character (Str)
- printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
- """
- percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
- filledLength = int(length * iteration // total)
- bar = fill * filledLength + '-' * (length - filledLength)
- print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=printEnd)
- # Print New Line on Complete
- if iteration == total:
- print()
-
- # 模拟一个需要花费时间的任务
- for i in range(100):
- time.sleep(0.01) # 假设每个迭代需要0.01秒
- print_progress_bar(i + 1, 100, prefix='Progress:', suffix='Complete', length=50)
在这个例子中,print_progress_bar
函数用于打印进度条。它接受当前迭代次数、总迭代次数和其他一些可选参数。在每次迭代中,我们调用这个函数来更新进度条。注意,我们在循环结束后添加了一个额外的换行符,以便在进度条完成后清除终端中的最后一行。
除了使用tqdm
库和纯Python的print
函数与time
库来模拟进度条之外,还有其他几种方法可以实现进度条。这里我将介绍两种额外的方法:
rich
库rich
库是一个用于创建丰富文本和漂亮终端输出的Python库,它也包括了一个强大的进度条功能。
首先,你需要安装rich
库:
pip install rich
然后,你可以使用以下代码来显示进度条:
- from rich.progress import Progress
- import time
-
- with Progress() as progress:
- task = progress.add_task("Processing...", total=100)
- for i in range(100):
- time.sleep(0.01) # 假设每个迭代需要0.01秒
- progress.update(task, advance=1)
效果:
Processing... ███████████▏ 50/100 [00:04<00:04, 11.97it/s]
click
库 click
库是一个用于创建命令行接口的库,它也提供了一个简单的进度条实现。
首先,你需要安装click
库:
pip install click
但是,请注意,click
的进度条主要用于命令行工具,并且可能不如tqdm
或rich
那么灵活。不过,如果你正在开发一个命令行工具,它可能是个不错的选择。
以下是一个使用click
库的简单示例:
- import click
- import time
-
- @click.command()
- def cli():
- with click.progressbar(range(100)) as bar:
- for item in bar:
- time.sleep(0.01) # 假设每个迭代需要0.01秒
-
- if __name__ == '__main__':
- cli()
在这个例子中,我们定义了一个cli
函数,并使用click.progressbar
上下文管理器来包装一个范围。在每次迭代中,进度条会自动更新。
以上介绍了四种不同的方法来实现Python中的进度条:使用tqdm
库、纯Python的print
函数与time
库、rich
库和click
库。每种方法都有其优缺点,你可以根据你的具体需求来选择最适合你的方法。如果你需要一个简单且易于使用的库,tqdm
可能是一个很好的选择。如果你需要更丰富的终端输出和更多的控制选项,rich
可能更适合你。如果你正在开发一个命令行工具,并且需要进度条功能,那么click
可能是一个好选择。
当然,还有其他方法可以实现Python中的进度条,尽管它们可能不如前面提到的库那样全面或易于使用。以下是一些额外的方法:
progressbar2
库progressbar2
是另一个流行的库,用于在Python中创建进度条。虽然它的功能可能与tqdm
相似,但如果你更喜欢这个库,可以尝试使用它。
首先,你需要安装progressbar2
库:
pip install progressbar2
然后,你可以使用以下代码来显示进度条:
- from progressbar import ProgressBar
- import time
-
- bar = ProgressBar(max_value=100)
- for i in range(100):
- time.sleep(0.01) # 假设每个迭代需要0.01秒
- bar.update(i + 1)
- bar.finish()
PySimpleGUI
库 PySimpleGUI
是一个用于创建图形用户界面(GUI)的库,但它也支持在控制台应用程序中显示进度条。这个库非常适合那些希望在控制台应用程序中添加更多交互性的用户。
首先,你需要安装PySimpleGUI
库:
pip install pysimplegui
然后,你可以使用以下代码来显示一个控制台进度条:
- import PySimpleGUI as sg
- import time
-
- # 创建一个进度条元素
- progress_bar = sg.ProgressBar(100, orientation='h', size=(50, 15), key='progressbar')
-
- # 创建一个窗口,其中包含进度条
- layout = [[progress_bar]]
- window = sg.Window('Progress Bar', layout)
-
- # 启动事件循环
- for i in range(101):
- event, values = window.read(timeout=100)
- progress_bar.update_bar(i + 1)
- time.sleep(0.01) # 假设每个迭代需要0.01秒
-
- # 关闭窗口
- window.close()
curses
库(Unix/Linux)在Unix和Linux系统上,你可以使用curses
库来创建文本用户界面,包括进度条。但是,请注意,curses
库在Windows上不可用。
首先,你需要确保你的系统上安装了curses
库(在大多数Linux发行版上都是预装的)。然后,你可以使用以下代码来显示一个基本的进度条:
- import curses
- import time
-
- def main(stdscr):
- # 清除屏幕
- stdscr.clear()
-
- # 初始化颜色对(可选)
- curses.start_color()
- curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
-
- # 创建一个进度条窗口
- height, width = stdscr.getmaxyx()
- progress_bar_width = 50
- progress_bar_start = (height // 2) - 1
- progress_bar_end = progress_bar_start + 1
-
- for i in range(101):
- # 清除进度条行
- stdscr.addstr(progress_bar_start, 0, ' ' * width)
-
- # 计算并显示进度条
- filled_length = int((i / 100.0) * progress_bar_width)
- stdscr.addstr(progress_bar_start, (width - progress_bar_width) // 2, '[' + '=' * filled_length + ' ' * (progress_bar_width - filled_length) + ']')
-
- # 刷新屏幕以显示更新
- stdscr.refresh()
-
- # 模拟进度
- time.sleep(0.01)
-
- # 等待用户按键退出
- stdscr.getkey()
-
- # 使用curses包装器运行main函数
- curses.wrapper(main)
这些方法提供了不同的方式来在Python中创建和显示进度条,你可以根据你的具体需求和目标平台来选择最适合你的方法。