简体   繁体   English

Python:如何在同一行打印,清除之前的文本?

[英]Python: How to print on same line, clearing previous text?

In Python you can print on the same line using \r to move back to the start of the line.在 Python 中,您可以在同一行上使用\r返回到行首进行打印。

This works well for progress bars or increasing precentage counters, eg: Python print on same line这适用于进度条或增加百分比计数器,例如: Python 在同一行打印

However when printing lines that may decrease in length, this leaves the previous lines text there, eg:但是,当打印长度可能会减少的行时,这会将前几行文本留在那里,例如:

import sys
for t in ['long line', '%']:
    sys.stdout.write(t + '\r')
sys.stdout.write('\n')

Leaves the terminal text as: %ong line .将终端文本保留为: %ong line

Whats the best way to write a shorter line after a longer one, when printing to the same line?打印到同一行时,在较长的行之后写较短的行的最佳方法是什么?

Along with \\r , the ansi-sequence \\033[K is needed - erase to end of line .\\r ,需要 ansi 序列\\033[K -擦除到行尾

This code works as expected.此代码按预期工作。

import sys
for t in ['long line', '%']:
    sys.stdout.write('\033[K' + t + '\r')
sys.stdout.write('\n')

Note, this doesn't work when the string includes tabs, you may want to replace:请注意,当字符串包含制表符时,这不起作用,您可能需要替换:

sys.stdout.write('\\033[K' + t + '\\r') with ... sys.stdout.write('\\033[K' + t + '\\r')与 ...

sys.stdout.write('\\033[K' + t.expandtabs(2) + '\\r')

I think the simplest way to do this is to write spaces over the characters.我认为最简单的方法是在字符上写空格。 For this, it'd be a good idea to write as many spaces are needed to cover the last line only.为此,最好写一些空格来仅覆盖最后一行。 Example:示例:

previousLength = 0
for t in ["long line", "%"]:
    print(" " * previousLength, end="\r") 
    print(t, end="\r")

    previousLength = len(t)

print("\n")

If you have been printing without a newline character at the end of your print, you can flush your latest print with:如果您在打印末尾没有换行符的情况下进行打印,则可以使用以下方式刷新最新打印:

print('\r\033[K', end='')

If you previously printed with a new line, you can use the ANSI escape code to move up one line and to the beginning of the line with:如果您之前打印了一个新行,您可以使用 ANSI 转义码向上移动一行并到达行首:

print('\033[F', end='')

You can then flush the line as before.然后您可以像以前一样冲洗管线。

An example usage:示例用法:

LINE_FLUSH = '\r\033[K'
UP_FRONT_LINE = '\033[F'
...
print(UP_FRONT_LINE + LINE_FLUSH + msg)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM