从 Linux/macOS 终端中的 Go 程序打印并使用回车 return 时清除该行的其余部分

Clearing the rest of the line while printing from Go program in Linux/macOS terminal and using carriage return

如果我像这样在 Go 中创建一个循环:

package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 10; i >= 0; i-- {
        fmt.Printf("Time out in %d seconds\r", i)
        time.Sleep(1 * time.Second)
    }
}

和 运行 Linux 或 macOS 终端中的程序,我会看到在第一次迭代中正确打印的行(Time out in 10 seconds),但在下一次迭代中(以及其他所有在这种情况下),由于要打印的字符串短了一个字符,因此我会将上一次迭代的剩余部分视为最后的附加 s 字符 - Time out in 9 secondssTime out in 8 secondss 等。

有没有一种简单的方法可以在打印下一行之前清除上一次迭代的打印行?

To specify the width of an integer, use a number after the % in the verb. By default, the result will be right-justified and padded with spaces.

使用 %2d 而不是 %d。它会解决你的问题。

package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 10; i >= 0; i-- {
        fmt.Printf("Time out in %2d seconds\r", i)
        time.Sleep(1 * time.Second)
    }
}

更新:

您还可以从您的 go 代码执行 printf 'c\e[3J' 命令来清理终端。

package main

import (
    "fmt"
    "os"
    "os/exec"
    "time"
)

var clearScreen = func() {
    cmd := exec.Command(`printf 'c\e[3J'`) // clears the scrollback buffer as well as the screen.
    cmd.Stdout = os.Stdout
    cmd.Run()
}

func main() {
    for i := 10; i >= 0; i-- {
        fmt.Printf("Time out in %2d seconds\r", i)
        time.Sleep(1 * time.Second)
        clearScreen()
    }
}