实现如下所示的状态栏:

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

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


当前回答

最简单的还是

import sys
total_records = 1000
for i in range (total_records):
    sys.stdout.write('\rUpdated record: ' + str(i) + ' of ' + str(total_records))
    sys.stdout.flush()

关键是将整数类型转换为字符串。

其他回答

根据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是项目总数

这是一个简单的0导入进度条形码

#!/usr/bin/python3
def progressbar(current_value,total_value,bar_lengh,progress_char): 
    percentage = int((current_value/total_value)*100)                                                # Percent Completed Calculation 
    progress = int((bar_lengh * current_value ) / total_value)                                       # Progress Done Calculation 
    loadbar = "Progress: [{:{len}}]{}%".format(progress*progress_char,percentage,len = bar_lengh)    # Progress Bar String
    print(loadbar, end='\r')                                                                         # Progress Bar Output

if __name__ == "__main__":
    the_list = range(1,301) 
    for i in the_list:
        progressbar(i,len(the_list),30,'■')
    print("\n")

进度: [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

使用@Mark-Rushakoff的答案,我想出了一个更简单的方法,不需要调用sys库。它适用于Python 3。Windows测试:

from time import sleep
for i in range(21):
    # the exact output you're looking for:
    print ("\r[%-20s] %d%%" % ('='*i, 5*i), end='')
    sleep(0.25)

你可以从PyPI获得一个名为progressbar的Python模块,它实现了这样的功能。如果您不介意添加依赖项,这是一个很好的解决方案。否则,就用其他答案吧。

一个简单的例子,如何使用它:

import progressbar
from time import sleep
bar = progressbar.ProgressBar(maxval=20, \
    widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
bar.start()
for i in xrange(20):
    bar.update(i+1)
    sleep(0.1)
bar.finish()

要安装它,可以使用easy_install progressbar,如果您更喜欢pip,则可以使用pip install progressbar。

最简单的还是

import sys
total_records = 1000
for i in range (total_records):
    sys.stdout.write('\rUpdated record: ' + str(i) + ' of ' + str(total_records))
    sys.stdout.flush()

关键是将整数类型转换为字符串。