前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 中的多种进度条实现方法

Python 中的多种进度条实现方法

作者头像
不止于python
发布2023-10-24 16:44:40
7790
发布2023-10-24 16:44:40
举报
文章被收录于专栏:不止于python不止于python

1. 文本进度条

文本进度条是在命令行界面中显示的一种基本的进度展示方法。可以使用字符或符号来构建文本进度条。这种方式很最简单, 就是使用print实现。

代码语言:javascript
复制
import time

def text_progress_bar(iteration, total, length=50):
    percent = ("{0:.1f}").format(100 * (iteration / float(total)))
    arrow = "=" * int(length * iteration // total)
    spaces = " " * (length - len(arrow))
    print(f"Progress: [{arrow + spaces}] {percent}% complete", end="\r")

total = 100
for i in range(total + 1):
    text_progress_bar(i, total)
    time.sleep(0.1)

2. tqdm 库

tqdm 是一个流行的Python库,用于创建各种进度条,支持多种风格和选项。

代码语言:javascript
复制
from tqdm import tqdm
import time

data = range(100)
for item in tqdm(data, desc="Processing"):
    time.sleep(0.05)

3. Progress 模块

progress 是一个Python库,用于创建不同类型的进度条,提供更多的样式和选项。

代码语言:javascript
复制
from progress.bar import Bar
import time

with Bar('Processing', max=100) as bar:
    for i in range(100):
        time.sleep(0.05)
        bar.next()

4. alive-progress 模块

alive-progress 是一个用于创建带有动画效果的进度条的库。

代码语言:javascript
复制
from alive_progress import alive_bar
import time

with alive_bar(100, bar="filling") as bar:
    for i in range(100):
        time.sleep(0.05)
        bar()

5. rich 模块

rich 模块可以实现漂亮和高度可定制的文本进度条。

代码语言:javascript
复制
from rich.progress import Progress
import time

def rich_progress_bar():
    with Progress() as progress:
        task = progress.add_task("[cyan]Processing...", total=100)
        while not progress.finished:
            progress.advance(task, advance=1)
            time.sleep(0.05)

rich_progress_bar()

6. progressbar模块

progressbarprogress 模块的增强版本,提供了更多的自定义选项和更多的进度条类型。

代码语言:javascript
复制
from progressbar import ProgressBar
import time

pbar = ProgressBar()
for i in pbar(range(100)):
   time.sleep(0.05)

这些示例展示了Python中实现进度条的多种方式,从简单的文本进度条到更复杂的库,可以选择适合项目的进度条方法。这些进度条可以让任务进度更可视化,并提高用户体验。当然还有一些其它的模块可以实现, 比如(PyInquirer,PySimpleGUI, Curses)等,但相对于以上模块实现起来比较麻烦, 以上模块基本可以是满足项目使用~

一直在努力, 记得点个在看哦!

本文参与?腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-10-22,如有侵权请联系?cloudcommunity@tencent.com 删除

本文分享自 不止于python 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 2. tqdm 库
  • 3. Progress 模块
  • 4. alive-progress 模块
  • 5. rich 模块
  • 6. progressbar模块
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com