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

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

最佳答案

尝试使用 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://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences

关于python - 使用\r 并打印一些文本后,如何清除控制台中的一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25142958/

相关文章:

python - 根据字符的出现对列表进行排序

linux - Bash 验证日期

Javascript console.log() 运行附加代码

winapi - GetConsoleScreenBufferInfoEx 由于参数无效而失败

c++ - Linux c++ 控制台获取关键状态

python - 如何跟踪嵌套装饰器的深度?

python - 将透明视频叠加到摄像机供稿OpenCV

linux - 安装 expat XML 解析器以在 Arm 板上使用蓝牙

linux - 如何从文件中的同一行随机选择字符串

python - 在numpy中将几个矩阵相乘