实现如下所示的状态栏:

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

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


当前回答

我发现有用的库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可以包装任何可迭代对象。

其他回答

在尝试了Mark Rushakoff的解决方案后,我今天看到了这个帖子

from time import sleep
import sys

for i in range(21):
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
sys.stdout.flush()
sleep(0.25)

我可以说这在使用python 3.4.3 64位的W7-64上工作得很好,但仅限于本机控制台。但是,当使用spyder 3.0.0dev的内置控制台时,换行符仍然/再次出现。由于我花了一些时间来弄清楚,我想在这里报告这一观察结果。

要成为纯python并且不进行系统调用:

from time import sleep

for i in range(21):
    spaces = " " * (20 - i)
    percentage = 5*i
    print(f"\r[{'='*i}{spaces}]{percentage}%", flush=True, end="")
    sleep(0.25)

根据上面的答案和其他类似的关于CLI进度条的问题,我想我得到了一个普遍的答案。请登录https://stackoverflow.com/a/15860757/2254146查看。

下面是这个函数的一个副本,但是为了适合你的风格进行了修改:

import time, sys

# update_progress() : Displays or updates a console progress bar
## Accepts a float between 0 and 1. Any int will be converted to a float.
## A value under 0 represents a 'halt'.
## A value at 1 or bigger represents 100%
def update_progress(progress):
    barLength = 20 # Modify this to change the length of the progress bar
    status = ""
    if isinstance(progress, int):
        progress = float(progress)
    if not isinstance(progress, float):
        progress = 0
        status = "error: progress var must be float\r\n"
    if progress < 0:
        progress = 0
        status = "Halt...\r\n"
    if progress >= 1:
        progress = 1
        status = "Done...\r\n"
    block = int(round(barLength*progress))
    text = "\rPercent: [{0}] {1}% {2}".format( "="*block + " "*(barLength-block), progress*100, status)
    sys.stdout.write(text)
    sys.stdout.flush()

看起来像

百分比:[====================]99.0%

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

PyProg试试。PyProg是Python的一个开源库,用于创建超级可定制的进度指示器和进度条。

它目前的版本是1.0.2;它托管在Github上,在PyPI上可用(链接如下)。它与Python 3和2兼容,也可以与Qt控制台一起使用。

它真的很容易使用。以下代码:

import pyprog
from time import sleep

# Create Object
prog = pyprog.ProgressBar(" ", " ", total=34, bar_length=26, complete_symbol="=", not_complete_symbol=" ", wrap_bar_prefix=" [", wrap_bar_suffix="] ", progress_explain="", progress_loc=pyprog.ProgressBar.PROGRESS_LOC_END)
# Update Progress Bar
prog.update()

for i in range(34):
    # Do something
    sleep(0.1)
    # Set current status
    prog.set_stat(i + 1)
    # Update Progress Bar again
    prog.update()

# Make the Progress Bar final
prog.end()

将产生你想要的(甚至是条长度!):

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

要了解更多自定义进度条的选项,请访问本网站的Github页面。

我实际上做了PyProg,因为我需要一个简单但超级可定制的进度条库。您可以轻松地使用:pip install pyprog安装它。

PyProg Github: https://github.com/Bill13579/pyprog 皮皮:https://pypi.python.org/pypi/pyprog/