在同一行写入输出,在 python 控制台上完全清除前一行

Write output in same line, clearing previous line completely on python console

此代码演示了一个进度并在同一控制台行打印 Done... 并退出程序

import time

filename = 'file-name.txt'

for i in range(0, 101):
    time.sleep(0.1)
    print('Downloading File %s [%d%%]\r'% (filename, i), end="", flush=True)

print('Done...\r\n', end="", flush=True)

问题是程序结束时,在最后一行的末尾有上一行的remnants。波纹管输出演示 单行 在程序 运行.

更新

当前输出(单行更新)

Downloading File file-name.txt [1%]
.
.
Downloading File file-name.txt [100%]
Done...ding File file-name.txt [100%]

预期输出(单行更新)

Downloading File file-name.txt [1%]
.
.
Downloading File file-name.txt [100%]
Done...

中发现了同样的问题,但它没有 解决 这个问题。 如果没有上一行的 remnant,我如何才能实现 Expected Output。 我想添加 '\b\b\b\b\b\b\b\b\b\b' 不是很 pythonic

我复制了您提供的代码并运行它在我的系统上.. 输出符合您的预期。

```Downloading File file-name.txt [0%]
Downloading File file-name.txt [1%]
Downloading File file-name.txt [2%]
Downloading File file-name.txt [3%]
Downloading File file-name.txt [4%]
Downloading File file-name.txt [5%]
Downloading File file-name.txt [6%]
Downloading File file-name.txt [7%]
Downloading File file-name.txt [8%]
Downloading File file-name.txt [9%]
Downloading File file-name.txt [10%]
Downloading File file-name.txt [11%]
Downloading File file-name.txt [12%]
Downloading File file-name.txt [13%]

Downloading File file-name.txt [100%]
Done... ```

这个 none 可打印字符 \x1b[2K 擦除当前行并解决了问题。

import time

filename = 'file-name.txt'

for i in range(0, 101):
    time.sleep(0.1)
    print('Downloading File %s [%d%%]\r'% (filename, i), end="", flush=True)

print('\x1b[2K', end="")
print('Done...\r\n', end="", flush=True)