我编写了一个简单的控制台应用程序,使用ftplib从FTP服务器上传和下载文件。

我想应用程序显示一些可视化的下载/上传进度为用户;每次下载数据块时,我希望它提供一个进度更新,即使它只是一个数字表示,如百分比。

重要的是,我想避免擦除之前打印到控制台的所有文本(即,我不想在打印更新的进度时“清除”整个终端)。

这似乎是一个相当常见的任务——我如何才能制作一个进度条或类似的可视化输出到我的控制台,同时保留之前的程序输出?


当前回答

http://code.activestate.com/recipes/168639-progress-bar-class/ (2002) http://code.activestate.com/recipes/299207-console-text-progress-indicator-class/ (2004) http://pypi.python.org/pypi/progressbar (2006)

还有很多教程等着你去谷歌。

其他回答

试试由Python界的莫扎特Armin Ronacher编写的点击库。

$ pip install click # both 2 and 3 compatible

创建一个简单的进度条:

import click

with click.progressbar(range(1000000)) as bar:
    for i in bar:
        pass 

这是它的样子:

# [###-------------------------------]    9%  00:01:14

定制您心中的内容:

import click, sys

with click.progressbar(range(100000), file=sys.stderr, show_pos=True, width=70, bar_template='(_(_)=%(bar)sD(_(_| %(info)s', fill_char='=', empty_char=' ') as bar:
    for i in bar:
        pass

自定义:

(_(_)===================================D(_(_| 100000/100000 00:00:02

还有更多的选项,请参阅API文档:

 click.progressbar(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None)
import sys
def progresssbar():
         for i in range(100):
            time.sleep(1)
            sys.stdout.write("%i\r" % i)

progressbar()

注意:如果你在交互式拦截器中运行这个,你会得到额外的数字打印出来

写入一个\r到控制台。这是一个“回车”,它使它之后的所有文本都在行首回显。喜欢的东西:

def update_progress(progress):
    print '\r[{0}] {1}%'.format('#'*(progress/10), progress)

这将给你一些像:[##########]100%

我意识到我在游戏中迟到了,但这里是我写的一个稍微有点yum风格的(Red Hat)(这里不是100%的准确性,但如果你使用进度条来达到这个准确度,那么你就错了):

import sys

def cli_progress_test(end_val, bar_length=20):
    for i in xrange(0, end_val):
        percent = float(i) / end_val
        hashes = '#' * int(round(percent * bar_length))
        spaces = ' ' * (bar_length - len(hashes))
        sys.stdout.write("\rPercent: [{0}] {1}%".format(hashes + spaces, int(round(percent * 100))))
        sys.stdout.flush()

应该产生如下所示的结果:

Percent: [##############      ] 69%

... 括号保持不变,只有哈希值增加。

作为装饰器,这可能会更好。再等一天……

http://code.activestate.com/recipes/168639-progress-bar-class/ (2002) http://code.activestate.com/recipes/299207-console-text-progress-indicator-class/ (2004) http://pypi.python.org/pypi/progressbar (2006)

还有很多教程等着你去谷歌。