为什么在使用缓冲区打印到标准输出时,ANSI转义码无法正常工作?

huangapple go评论91阅读模式
英文:

Go : Why do ANSI exscape codes not work when using the buffer to print to std.out?

问题

所以我正在尝试将项目打印到命令行,并且我希望能够快速完成,所以我正在使用这种方法将内容打印到cmd,因为它比fmt.print更快:

buf := bufio.NewWriter(os.Stdout)
fmt.Fprint(buf, "text here")

我运行了几个测试,这是打印到屏幕的最快方法。但是有一个问题,我还想打印ANSI转义码来移动光标、更改颜色等。

这段代码是有效的,它应该将光标位置移动到0,0,而且确实可以实现:

fmt.Printf("3[%d;%dH", 0, 0)

然而,当我尝试使用缓冲区来实现相同的效果时,它什么也不做:

start := fmt.Sprintf("3[%d;%dH", 0, 0)
buf := bufio.NewWriter(os.Stdout)
fmt.Fprint(buf, start)

我在这里做错了什么?有没有办法使用缓冲区来实现这个效果?非常感谢。

这是在Windows 11上使用cmd而不是PowerShell完成的。

英文:

So I am trying to get items to print to the command line and I want to do it quickly, so I am using this method to print to cmd as it is quicker than fmt.print :

buf := bufio.NewWriter(os.Stdout)
fmt.Fprint(buf, "text here")

I have run several tests and this is the quickest method of printing to the screen. But there is an issue, I also want to print ansi escape codes to move the cursor around, change colours etc.

This piece of code works, what it should do is move the cursor position to 0,0 and it does

fmt.Printf("3[%d;%dH", 0, 0)

However when I try to use the buffer to achieve the same it does nothing

start := fmt.Sprintf("3[%d;%dH", 0, 0)
buf := bufio.NewWriter(os.Stdout)
fmt.Fprint(buf, start)

What am I doing wrong here? Is there a way to achieve this using the buffer? Many thanks

This was done on windows 11 using cmd, not powershell

答案1

得分: 0

好的,我会为你翻译以下内容:

好的,我打印出了多余的一行,导致当返回到0,0时数据没有被覆盖,我觉得x,y是相对于视口的,所以数据滚动到了屏幕外。

不同的行为确实是由于没有刷新缓冲区引起的。所以在我打印到屏幕的for循环中包含一个刷新操作修复了这个问题。

英文:

Ok, I was printing out 1 row too many and this was causing data to not be overwritten when returning to 0,0, I get the impression that x, y is relative to the view port so data was scrolling off screen.

The different behaviour was indeed caused by not flushing the buffer. So including a flush in the for loop where I was printing to the screen fixed that.

huangapple
  • 本文由 发表于 2022年6月19日 06:11:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/72673093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定