用Python替换控制台输出

时间:2011-05-29 17:25:17

标签: python

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

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

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

最简单的更新是什么?

X things done.

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

11 个答案:

答案 0 :(得分:109)

一个简单的解决方案就是在字符串前写"\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()

答案 1 :(得分:25)

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

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%

答案 2 :(得分: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

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

答案 3 :(得分:7)

我前一段时间写了这篇文章,对此我感到非常满意。随时使用它。

它需要一个indextotal以及可选的titlebar_length。完成后,用复选标记替换沙漏。

⏳ Calculating: [████░░░░░░░░░░░░░░░░░░░░░] 18.0% done

✅ Calculating: [█████████████████████████] 100.0% done

我提供了一个可以运行以对其进行测试的示例。

import sys
import time

def print_percent_done(index, total, bar_len=50, title='Please wait'):
    '''
    index is expected to be 0 based index. 
    0 <= index < total
    '''
    percent_done = (index+1)/total*100
    percent_done = round(percent_done, 1)

    done = round(percent_done/(100/bar_len))
    togo = bar_len-done

    done_str = '█'*int(done)
    togo_str = '░'*int(togo)

    print(f'\t⏳{title}: [{done_str}{togo_str}] {percent_done}% done', end='\r')

    if round(percent_done) == 100:
        print('\t✅')


r = 50
for i in range(r):
    print_percent_done(i,r)
    time.sleep(.02)

我也有一个版本,该版本带有响应进度栏,具体取决于终端宽度,请使用shutil.get_terminal_size()

答案 4 :(得分:6)

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

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

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

答案 5 :(得分:6)

对于那些多年后偶然发现的人(就像我一样),我稍微调整了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 :(得分: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

答案 7 :(得分:2)

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

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

对跟踪最新更新和进度特别有用。

我也建议使用tqdm from here,以查看循环的进度。它将当前迭代和总迭代打印为进度条,并带有预期的完成时间。超级有用且快速。适用于python2和python3。

答案 8 :(得分:1)

如果我们查看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)

答案 9 :(得分:0)

from time import sleep

max_val = 40

for done in range(max_val):
    sleep(0.05)

    undone = max_val - 1 - done
    proc = (100 * done) // (max_val - 1)
    print(f"\rProgress: [{('#' * done) + ('_' * undone)}] ({proc}%)", end='\r')

print("\nDone!")
Progress: [###################_____________________] (47%)
Progress: [########################################] (100%)
Done!

答案 10 :(得分:-1)

下面的代码将在0.3秒内将消息从0计数到137,从而替换以前的数字。

要后台处理的符号数=数字位数。

APP RUN -> Check if row exists in user table

if YES ->  return Home();
else -> return SignIn();