【问题标题】:Write output in same line, clearing previous line completely on python console在同一行写入输出,在 python 控制台上完全清除前一行
【发布时间】:2021-04-20 17:37:57
【问题描述】:

这段代码演示了一个进度并在同一控制台行打印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...

here 中发现了同样的问题,但它并没有解决这个问题。 如果没有前一行的remnant,我怎样才能实现预期输出。 我想添加'\b\b\b\b\b\b\b\b\b\b' 不是很pythonic

【问题讨论】:

  • 我似乎误解了你的问题。我将删除我的答案。
  • @GoodDeeds 感谢您的帮助

标签: python-3.x console command-line-interface stdout python-curses


【解决方案1】:

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

```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... ```

【讨论】:

  • 输出显示上一行的剩余部分,我在你回答后编辑了代码以更清楚地展示它
【解决方案2】:

这个不可打印的字符 \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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 2011-02-23
    相关资源
    最近更新 更多