在Python中打印进度条处理

Gia*_*ear 4 python printing progress-bar

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

    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)
Run Code Online (Sandbox Code Playgroud)

我无法修复的问题是第一次打印所有点时(例如:处理....如果索引等于5),光标不会从零开始.

Joh*_*ann 6

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

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

上面的代码可能会导致一些短暂的闪烁.在您的特定情况下,当n % index变为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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

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()
Run Code Online (Sandbox Code Playgroud)

编辑2:或者如果您希望光标始终位于行的开头:

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

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

  • @Gianni:结合3和2:将第二个最后一行从解决方案2复制到`sys.stdout.flush()`之前的解决方案3中. (2认同)
  • 是的,我知道,这很好.你还可以做的是在字符串的末尾添加一个`\ r``.这会将光标始终移动到行的开头.但这是一个偏好问题.这样做的另一个好处是,当您打印下一行时,您可以覆盖进度条.但我猜这又是一个偏好问题.我根据Daniels的建议更新了答案. (2认同)