在 Python 中打印进度条处理 [英] print a progress-bar processing in Python

查看:49
本文介绍了在 Python 中打印进度条处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这个简单的函数processing_flush",以便打印一系列点(由索引给出)来测试我的软件是否正在处理我的数据以及最终的速度.我的数据总大小未知.

I wrote this simple function "processing_flush" in order to print a sequence of points (given by index) to test if my software is processing my data and eventually the speed. The total size of my data is unknown.

    import sys
    import time

    def processing_flush(n, index=5):
        sys.stdout.write("\rProcessing %s" % ((n % index)* "."))
        sys.stdout.flush()

    for n in xrange(20):
        processing_flush(n, index=5)
        time.sleep(1)

我无法解决的问题是第一次打印所有点时(例如:Processing .... 如果索引等于 5)光标不是从零开始.

The problem that i cannot fix is when all points are printed the first time (ex: Processing .... if index is equal to 5) the cursor doesn't start from zero.

推荐答案

在再次覆盖同一行之前,您至少需要清除点与空格的位置.

Before you overwrite the same line again you need to clear at least the positions where the dots are with spaces.

def processing_flush(n, index=5):
    sys.stdout.write("\rProcessing %s" % (index * " "))
    sys.stdout.write("\rProcessing %s" % ((n % index)* "."))
    sys.stdout.flush()

上面的代码可能会导致一些短暂的闪烁.在您的特定情况下,当 n % index 变为 0 时,清除该行就足够了:

The code above may lead to some brief flicker. In your specific case it is sufficient to clear the line when n % index becomes 0:

def processing_flush(n, index=5):
    if n % index == 0:
        sys.stdout.write("\rProcessing %s" % (index * " "))
    sys.stdout.write("\rProcessing %s" % ((n % index)* "."))
    sys.stdout.flush()

或者更好的是总是写 index-1 字符:

Or even better always write index-1 characters:

def processing_flush(n, index=5):
    sys.stdout.write("\rProcessing %s%s" % ((n % index)* ".", (index - 1 - (n % index))* " "))
    sys.stdout.flush()

编辑 1: 或者,如果您希望光标始终位于最后一个点之后:

Edit 1: Or if you prefer to have the cursor always after the last dot:

def processing_flush(n, index=5):
    sys.stdout.write("\rProcessing %s%s" % ((n % index)* ".", (index - 1 - (n % index))* " "))
    sys.stdout.write("\rProcessing %s" % ((n % index)* "."))
    sys.stdout.flush()

编辑 2: 或者,如果您希望光标始终位于行首:

Edit 2: Or if you prefer to have the cursor always at the beginning of the line:

def processing_flush(n, index=5):
    sys.stdout.write("Processing %s%s\r" % ((n % index)* ".", (index - 1 - (n % index))* " "))
    sys.stdout.flush()

原因是如果你只覆盖前一行的第一部分,你的 shell 会记住上一行的剩余字符.

The reason is that your shell remembers the remaining characters of the previous line if you overwrite just the first part of it.

这篇关于在 Python 中打印进度条处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆