用Python替换控制台输出

问题描述 投票:75回答:8

我想知道如何在Python中创建一个漂亮的控制台计数器,就像在某些C / C ++程序中一样。

我有一个循环做事,当前的输出是这样的:

Doing thing 0
Doing thing 1
Doing thing 2
...

什么是最简单的就是让最后一行更新;

X things done.

我在许多控制台程序中看到过这种情况,我想知道是否/如何在Python中执行此操作。

python
8个回答
114
投票

一个简单的解决方案就是在字符串之前编写"\r"而不添加换行符;如果字符串永远不会变短,这就足够了......

sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

进度条稍微复杂一点......这是我正在使用的东西:

def startProgress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
    sys.stdout.flush()
    progress_x = 0

def progress(x):
    global progress_x
    x = int(x * 40 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x

def endProgress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

你打电话给startProgress传递操作的描述,然后progress(x)在哪里x是百分比,最后endProgress()


28
投票

更优雅的解决方案可能是:

def progressBar(value, endvalue, bar_length=20):

        percent = float(value) / endvalue
        arrow = '-' * int(round(percent * bar_length)-1) + '>'
        spaces = ' ' * (bar_length - len(arrow))

        sys.stdout.write("\rPercent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100))))
        sys.stdout.flush()

用value和endvalue调用这个函数,结果应该是

Percent: [------------->      ] 69%

7
投票

另一个答案可能更好,但这就是我在做的事情。首先,我创建了一个名为progress的函数,用于打印退格字符:

def progress(x):
    out = '%s things done' % x  # The output
    bs = '\b' * 1000            # The backspace
    print bs,
    print out,

然后我在主函数的循环中调用它,如下所示:

def main():
    for x in range(20):
        progress(x)
    return

这当然会抹掉整条线,但是你可以把它搞得一团糟去做你想要的。我最终使用这种方法制作了一个进度条。


7
投票

对于那些多年后偶然发现的人(就像我一样),我稍微调整了6502的方法,以允许进度条减少和增加。在更多的情况下有用。感谢6502一个伟大的工具!

基本上,唯一的区别是每次调用progress(x)时都会写入#s和-s的整行,并且光标总是返回到条的开头。

def startprogress(title):
    """Creates a progress bar 40 chars long on the console
    and moves cursor back to beginning with BS character"""
    global progress_x
    sys.stdout.write(title + ": [" + "-" * 40 + "]" + chr(8) * 41)
    sys.stdout.flush()
    progress_x = 0


def progress(x):
    """Sets progress bar to a certain percentage x.
    Progress is given as whole percentage, i.e. 50% done
    is given by x = 50"""
    global progress_x
    x = int(x * 40 // 100)                      
    sys.stdout.write("#" * x + "-" * (40 - x) + "]" + chr(8) * 41)
    sys.stdout.flush()
    progress_x = x


def endprogress():
    """End of progress bar;
    Write full bar, then move to next line"""
    sys.stdout.write("#" * 40 + "]\n")
    sys.stdout.flush()

6
投票

如果我理解得很好(不确定)你想用<CR>而不是<LR>打印?

如果是这样,这是可能的,只要控制台终端允许这样(当输出si重定向到文件时它会中断)。

from __future__ import print_function
print("count x\r", file=sys.stdout, end=" ")

4
投票

如果我们查看print()函数,可以在不使用sys库的情况下完成

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

这是我的代码:

def update(n):
    for i in range(n):
        print("i:",i,sep='',end="\r",flush=True)
        #time.sleep(1)

3
投票

为Aravind Voggu的示例添加了更多功能:

def progressBar(name, value, endvalue, bar_length = 50, width = 20):

        percent = float(value) / endvalue

        arrow = '-' * int(round(percent*bar_length) - 1) + '>'

        spaces = ' ' * (bar_length - len(arrow))

        sys.stdout.write("\r{0: <{1}} : [{2}]{3}%".format(\
                         name, width, arrow + spaces, int(round(percent*100))))

        sys.stdout.flush()

        if value == endvalue:        

             sys.stdout.write('\n\n')

现在,您可以生成多个进度条而无需替换之前的一次。 我还将名称添加为具有固定宽度的值。

对于两个循环和两次使用progressBar(),结果将如下所示:

enter image description here


2
投票

在python 3中,您可以执行此操作以在同一行上打印:

print('', end='\r')

特别适用于跟踪最新的更新和进度。

如果想看到循环的进展,我也会推荐tqdm from here。它将当前迭代和总迭代打印为具有预期完成时间的进度条。超级实用,快捷。适用于python2和python3。

© www.soinside.com 2019 - 2024. All rights reserved.