如何在控制台使用\r打印文字后清除一行?

6

针对我的当前项目,有一些代码片段速度较慢且我无法加快其速度。为了获得一些反馈,了解已完成的进度和剩余工作量,我创建了一个进度代码片段,如下所示。

当您查看最后一行时

sys.stdout.write("\r100%" + " "*80 + "\n")

我使用" "*80来覆盖剩余的字符。有更好的清除行的方法吗?

(如果您发现剩余时间的计算错误,我也会很高兴。但这是另一个问题。)

进度片段

#!/usr/bin/env python

import time
import sys
import datetime


def some_slow_function():
    start_time = time.time()
    totalwork = 100
    for i in range(totalwork):
        # The slow part
        time.sleep(0.05)
        if i > 0:
            # Show how much work was done / how much work is remaining
            percentage_done = float(i)/totalwork
            current_running_time = time.time() - start_time
            remaining_seconds = current_running_time / percentage_done
            tmp = datetime.timedelta(seconds=remaining_seconds)
            sys.stdout.write("\r%0.2f%% (%s remaining)   " %
                             (percentage_done*100, str(tmp)))
            sys.stdout.flush()
    sys.stdout.write("\r100%" + " "*80 + "\n")
    sys.stdout.flush()

if __name__ == '__main__':
    some_slow_function()

控制台

我大多数情况下使用ZSH,有时使用bash(我总是在Linux系统上)


取决于你的控制台是什么类型。例如,Unix VT100 类型的控制台与 Windows 控制台具有完全不同的行清除语义。 - Marc B
你为什么问是否有更好的方法?当你尝试这种方式时会发生什么? - Robᵩ
@Robᵩ:问题在于我必须知道我需要覆盖多少。 - Martin Thoma
@MarcB:我使用ZSH和Bash(而且我总是在Linux系统上)。 - Martin Thoma
所以请查阅 ANSI/VT100 终端控制序列。 - Marc B
2个回答

13

尝试使用ANSI/vt100的“清除至行尾”转义序列:

sys.stdout.write("\r100%\033[K\n")

演示:

for i in range(4):
    sys.stdout.write("\r" + ("."*i*10))
    sys.stdout.flush()
    if i == 3:
        sys.stdout.write("\rDone\033[K\n")
    time.sleep(1.5)

参考: https://zh.wikipedia.org/wiki/ANSI转义序列#CSI_code


0

这是我使用的

from msvcrt import putch, getch

def putvalue(value):
   for c in str(value):
      putch(c)

def overwrite(value):
   """ Used to overwrite the current line in the command prompt,
   useful when displaying percent or progress """
   putvalue('\r'+str(value))

from time import sleep


for x in xrange(101):
   overwrite("Testing Overwrite.........%s%% complete" % x)
   sleep(.05)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接