实现如下所示的状态栏:

[==========                ]  45%
[================          ]  60%
[==========================] 100%

我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?


当前回答

import progressbar
import time

# Function to create  
def animated_marker():
    widgets = ['Loading: ', progressbar.Bar('=', '[', ']', '-'), progressbar.Percentage()]
    bar = progressbar.ProgressBar(max_value=200,widgets=widgets).start() 
      
    for i in range(200): 
        time.sleep(0.1)
        bar.update(i+1)
    bar.finish()

# Driver's code 
animated_marker()

其他回答

根据Steven C. Howell对Mark Rushakoff回答的评论

j = (i + 1) / n
stdout.write('\r')
stdout.write('[%-20s] %d%%' % ('='*int(20*j), 100*j))
stdout.flush()

其中I是当前项目n是项目总数

下面是我使用@Mark-Rushakoff的解决方案制作的一些东西。自适应调整到终端宽度。

from time import sleep
import os
import sys
from math import ceil

l = list(map(int,os.popen('stty size','r').read().split()))
col = l[1]
col = col - 6

for i in range(col):
    sys.stdout.write('\r')
    getStr = "[%s " % ('='*i)
    sys.stdout.write(getStr.ljust(col)+"]"+"%d%%" % (ceil((100/col)*i)))
    sys.stdout.flush()
    sleep(0.25)
print("")

我发现有用的库tqdm (https://github.com/tqdm/tqdm/,以前是:https://github.com/noamraph/tqdm)。它可以自动估计完成时间,也可以用作迭代器。

用法:

import tqdm
import time

for i in tqdm.tqdm(range(1000)):
    time.sleep(0.01)
    # or other long operations

结果:

|####------| 450/1000  45% [elapsed: 00:04 left: 00:05, 99.15 iters/sec]

TQDM可以包装任何可迭代对象。

对于Python 3.6,以下工作为我更新输出内联:

for current_epoch in range(10):
    for current_step) in range(100):
        print("Train epoch %s: Step %s" % (current_epoch, current_step), end="\r")
print()

只使用内置的sys:

import sys

def print_progress_bar(index, total, label):
    n_bar = 50  # Progress bar width
    progress = index / total
    sys.stdout.write('\r')
    sys.stdout.write(f"[{'=' * int(n_bar * progress):{n_bar}s}] {int(100 * progress)}%  {label}")
    sys.stdout.flush()

用法:

foo_list = ["a", "b", "c", "d"]
total = len(foo_list)

for index, item in enumerate(foo_list):
    print_progress_bar(index, total, "foo bar")
    sleep(0.5)

Enumerate (foo_list)使您可以在循环期间访问索引值。

输出:

[================================================  ] 96%  foo bar