无名阁,只为技术而生。流水不争先,争的是滔滔不绝。

(python 进度条) Python 实现进度条的六种方式 进度条实现方式有多种选择 全网首发(图文详解1)

前沿技术 Micheal 4个月前 (06-01) 48次浏览 已收录 扫描二维码

(python 进度条) Python 实现进度条的六种方式

在Python中实现进度条有多种方式,以下是六种常见的方法:

  • 使用内置的 print 函数手动打印进度条
import time
import sys

def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filled_length = int(length * iteration // total)
    bar = fill * filled_length + '-' * (length - filled_length)
    sys.stdout.write(f'\r{prefix} |{bar}| {percent}% {suffix}')
    sys.stdout.flush()
    if iteration == total: 
        print()

# 示例用法:
items = list(range(0, 57))
l = len(items)

# 初始调用函数以打印初始进度条
print_progress_bar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
for i, item in enumerate(items):
    # 执行一些任务
    time.sleep(0.1)
    # 更新进度条
    print_progress_bar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)

tqdm 是一个快速、可扩展的Python进度条库。

# 需要先安装tqdm库
# pip install tqdm

from tqdm import tqdm
import time

# 可以直接在for循环上使用tqdm()包装任何可迭代的对象
for i in tqdm(range(100)):
    # 模拟任务执行
    time.sleep(0.1)
  • 使用 progress

progress 是另一个用于创建进度条的库。

# 需要先安装progress库
# pip install progress

from progress.bar import Bar
import time

bar = Bar('Processing', max=20)
for i in range(20):
    # Do some work
    time.sleep(1)
    bar.next()
bar.finish()
  • 使用 alive-progress
# 需要先安装alive-progress库
# pip install alive-progress

from alive_progress import alive_bar
import time

items = range(100)  # replace with your real workload
with alive_bar(len(items)) as bar:
    for item in items:
        # process each item
        time.sleep(0.1)  # simulate some work
        bar()           # call after consuming one item
  • 利用 progressbar2
# 需要先安装progressbar2库
# pip install progressbar2

import progressbar
import time

widgets=[
    ' [', progressbar.Timer(), '] ',
    progressbar.Bar(),
    ' (', progressbar.ETA(), ') ',
]
bar = progressbar.ProgressBar(maxval=20, widgets=widgets).start()
for i in range(20):
    # do some work
    time.sleep(0.5)
    bar.update(i+1)
bar.finish()
  • 使用 rich
# 需要先安装rich库
# pip install rich

from rich.progress import Progress
import time

with Progress() as progress:
    task1 = progress.add_task("[red]Downloading...", total=1000)

    while not progress.finished:
        progress.update(task1, advance=5)
        time.sleep(0.02)

每种方法都有它们的配置流程和详细代码,通常在使用第三方库的时候,你需要先通过pip安装它们。上述示例给出了基本的使用方法和代码结构,你可以根据自己的需求进行详细的配置过程和代码调整。
(torch.randn()) pytorch常用函数之torch.randn()解读 torch.randn() 函数简介 全网首发(图文详解1)
(inplace) 对PyTorch中inplace字段的全面理解 inplace 操作在 PyTorch 中的重要作用 全网首发(图文详解1)

喜欢 (0)
[]
分享 (0)
关于作者:
流水不争先,争的是滔滔不绝