如何在使用\ r \ n并打印一些文本后清除控制台中的一行?

时间:2014-08-05 15:41:36

标签: python linux console

对于我当前的项目,有些代码片段速度很慢,而且我无法加快速度。为了获得一些反馈已完成/必须完成的工作,我已经创建了一个进度代码段,您可以在下面看到。

当你看最后一行时

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系统上)

2 个答案:

答案 0 :(得分:8)

尝试使用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)

参考:http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes

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