简体   繁体   English

在Python中从sys.stdout清除旧数据

[英]Clearing old data from sys.stdout in Python

There's something I don't get when writing to sys.stdout in Python.What I want is to write some strings into stdout without preprending the stuff which already has been written before that. 用Python编写sys.stdout时我没有得到什么,我想要的是将一些字符串写到stdout中而不预先准备之前已经写过的东西。

So doing this: 这样做:

 while True:

    sys.stdout.write("k")
    sys.stdout.flush()

 sys.stdout.write("d")

After some "k" data has been written into stdout in a loop I need to write some new data afterwards,which is "d" for the sake of example. 在循环中将一些“ k”数据写入标准输出后,我需要随后再写入一些新数据,为示例起见,该数据为“ d”。 I am getting : "kd" in the output."K" from the loop writes is still in stdout. 我得到:输出中的“ kd”。循环写入中的“ K”仍在stdout中。

What I want to get is just "d" . 我想要得到的只是“ d”。

Why? 为什么? How can I clear the stdout before writing new data into it? 在将新数据写入stdout之前,如何清除它?

Btw,using print() instead still accumulates the old data into final output. 顺便说一句,使用print()仍然会将旧数据累积到最终输出中。

Using python 2.7 on Linux 在Linux上使用python 2.7

Terminals don't work that way. 终端不能那样工作。 flush just flushes the buffer (ie characters that may not have been printed to screen yet), it does not clear the screen. flush仅刷新缓冲区 (即可能尚未打印到屏幕上的字符),它不会清除屏幕。

If you want to erase one character, you need to print a literal backspace control character, and then print something over your previous output (like a space): 如果要删除一个字符,则需要打印一个原义的退格控制字符,然后以前的输出上打印一些内容(例如空格):

sys.stdout.write("\b ")

However. 然而。 Your asking this belies a deep misunderstanding of how terminals work. 您的要求掩盖了对终端工作原理的深刻误解。 Think of it like a text processor - there is text on the screen, and a cursor (which is invisible). 可以将其视为一个文本处理器-屏幕上有文本,并且有一个光标(不可见)。 You need to tell the cursor what to do to manipulate the text on the screen. 您需要告诉光标如何操作屏幕上的文本。 Since the cursor is always in overwrite mode, a trick that is often useful is to go back to the start of the line: 由于游标始终处于覆盖模式,因此通常有用的技巧是返回到行首:

 sys.stdout.write("\r")

and overwrite your data on that line. 并覆盖该行上的数据。 Note that if your new data is of lesser length than your previous data, this will leave some amount of previous data on the screen. 请注意,如果您的新数据的长度小于以前的数据,这将在屏幕上保留一些以前的数据。

There are other tricks you can use if neither of these fits your bill, like outputting terminal control sequences to stdout. 如果这些都不适合您,还可以使用其他技巧,例如将终端控制序列输出到stdout。

(also, unless you have a specific need for using sys.stdout , just use print .) (此外,除非您特别需要使用sys.stdout ,否则只需使用print 。)

I do have to print "k" but one line before "d".I want to print "d" in a completely new line. 我确实必须打印“ k”,但必须在“ d”之前打印一行。我想在全新的行中打印“ d”。

Simply write a newline between the two: 只需在两者之间写一个换行符:

sys.stdout.write("\n")

Or just use print , which adds an implicit newline at the end: 或只使用print ,它在末尾添加一个隐式换行符:

print "k"
print "d"

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

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