Python:如何在同一行打印,清除以前的文本? [英] Python: How to print on same line, clearing previous text?
问题描述
在 Python 中,您可以使用 \r
在同一行上打印以移回行首.
In Python you can print on the same line using \r
to move back to the start of the line.
这适用于进度条或增加百分比计数器,例如:Python 打印在同一行
This works well for progress bars or increasing precentage counters, eg: Python print on same line
然而,当打印长度可能减少的行时,这会将前一行文本留在那里,例如:
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')
保留终端文本为:%ong line
.
在打印到同一行时,在较长的一行之后写一条较短的行的最佳方法是什么?
Whats the best way to write a shorter line after a longer one, when printing to the same line?
推荐答案
与 \r
一起,需要 ansi-sequence \033[K
- 擦除到行尾.
Along with \r
, the ansi-sequence \033[K
is needed - erase to end of line.
此代码按预期工作.
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.expandtabs(2) + '\r')
这篇关于Python:如何在同一行打印,清除以前的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!