简体   繁体   English

Python 3.8:覆盖并清除终端中先前的较短行

[英]Python 3.8: Overwrite and clear previous shorter line in terminal

I am trying to overwrite the previously printed terminal line with a shorter print than before.我试图用比以前更短的打印覆盖以前打印的终端行。 I had a look at the article Remove and Replace Printed items and tried to figure out how to make it work for a shorter print, but the given tips are just working if the previous line is shorter than the text of the new print.我看了文章删除和替换打印的项目,并试图弄清楚如何使它适用于更短的打印,但是如果前一行比新打印的文本短,给定的提示只是工作。 Meaning:意义:

print('Test', end='\r')
print('TestTest')

prints Test first and then TestTest into the same line but首先将Test打印到同一行,然后将TestTest打印到同一行,但

print('Tessst', end='\r')
print('Test')

prints Tessst first and then Testst where it keeps the last two characters of the first print.首先打印Tessst ,然后Testst ,它保留第一次打印的最后两个字符。 I also tried to use sys.stdout.flush() (which apparently is for older Python versions) and the print option flush=True but neither of them worked.我还尝试使用sys.stdout.flush() (这显然适用于较旧的 Python 版本)和打印选项flush=True但它们都不起作用。 Is there another approach to make it work?是否有另一种方法可以使其发挥作用?

I have found a decent work around for this problem.我为这个问题找到了一个体面的工作。 You can just fill the end of the string with white spaces with f strings.您可以只用 f 字符串的空格填充字符串的末尾。 The full code for the problem I stated in the question would then be:我在问题中陈述的问题的完整代码将是:

print('Tessst', end='\r')
print(f'{"Test" : <10}')

I found this way here我在这里找到了这种方式

flush() just means that all the printed data should be written to the output stream. flush() 只是意味着所有打印的数据都应该写入 output stream。 It doesn't relate to what you're trying to do.它与您尝试做的事情无关。

If you want to overwrite the current line, you can put space characters after your second print to blank out the character cells on the screen.如果要覆盖当前行,可以在第二次打印后放置空格字符以清除屏幕上的字符单元格。 Or, if you have a fancy terminal like Xterm or a VT emulator, there is an escape sequence which will cause the rest of the line to be deleted:或者,如果您有像 Xterm 或 VT 仿真器这样的精美终端,则有一个转义序列会导致该行的 rest 被删除:

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

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

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