Golang如何拥有一个在stdout中更新的就地字符串? [英] Golang how to have an inplace string that updates at stdout?

查看:88
本文介绍了Golang如何拥有一个在stdout中更新的就地字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输出到标准输出并使输出覆盖前一个输出。



例如:如果我输出 On 1/10 ,我希望下一个输出 On 2/10 覆盖 1/10 。如何才能做到这一点?

解决方案

stdout code> io.Writer )。您无法修改已写入的内容。什么可以改变是如何将这个流代表打印到终端的情况。请注意,假设这种情况没有什么好的理由。例如,用户可以将stdout重定向到管道或任意文件。



因此,正确的方法是首先检查:




  • 如果stdout发送到终端

  • 那个终端的程序覆盖一行/屏幕



以上两个都不在这个问题的范围内,但我们假设终端是我们的设备。然后通常打印:

  fmt.Printf(\rOn%d / 10,i)

会覆盖终端中的上一行。 \r 代表回车,由许多终端实现将光标移动到当前行的开始位置,因此提供了覆盖线设施。



作为其他终端具有不同支持的覆盖的示例,以下是 playground


I want to output to stdout and have the output "overwrite" the previous output.

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 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:

  • if the stdout is going to a terminal
  • what is that terminal's procedure to overwrite a line/screen

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)

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.

这篇关于Golang如何拥有一个在stdout中更新的就地字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆