如何具有在标准输出上更新的就地字符串 [英] How to have an in-place string that updates on stdout
问题描述
我想输出到stdout并让输出覆盖"先前的输出.
I want to output to stdout and have the output "overwrite" the previous output.
例如;如果我输出 On 1/10
,我希望下一个输出 On 2/10
覆盖 On 1/10
.我该怎么办?
For example; if I output On 1/10
, I want the next output On 2/10
to overwrite On 1/10
. How can I do this?
推荐答案
stdout
是流( io.Writer
).您无法修改已写入的内容. 可以更改的是在流打印到终端的情况下该流的表示方式.请注意,没有充分的理由假设这种情况.例如,用户可以将stdout随意重定向到管道或文件.
stdout
is a stream (io.Writer
). You cannot modify what was already written to it. What can be changed is how that stream's represented in case it is printed to a terminal. Note that there's no good reason to assume this scenario. For example, a user could redirect stdout to a pipe or to a file at will.
所以正确的方法是先检查:
So the proper approach is to first check:
- 如果stdout要去终端机
- 该终端覆盖行/屏幕的程序是什么
以上两个都不在这个问题的范围内,但让我们假设终端是我们的设备.然后通常进行打印:
Both of the above are out of this question's scope, but let's assume that a terminal is our device. Then usually, printing:
fmt.Printf("\rOn %d/10", i)
将覆盖终端中的前一行. \ r
代表 carriage return
,由许多终端实现,将光标移动到当前行的开头,从而提供覆盖行"功能.
will overwrite the previous line in the terminal. \r
stands for carriage return
, implemented by many terminals as moving the cursor to the beginning of the current line, hence providing the "overwrite line" facility.
作为具有不同支持的覆盖"的其他"终端的示例,请参见游乐场.
As an example of "other" terminal with a differently supported 'overwriting', here is an example at the playground.
这篇关于如何具有在标准输出上更新的就地字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!