doulu1544 2019-05-12 21:56
浏览 450

如何使用Go在stdout中将格式化的字符串打印到同一行?

I am iterating over an array and printing a formatted string with each array element to the terminal (stdout). Rather than printing each element on a new line, I want to overwrite the previous output with the program's newest output.

I am using macosx.

I have tried a few ways:

// 'f' is the current element of the array
b := bytes.NewBufferString("")
if err != nil {
    fmt.Printf("Could not retrieve file info for %s
", f)
    b.Reset()
} else {
    fmt.Printf("Retrieved %s
", f)
    b.Reset()
}

A second way was to remove from the string and add and additional Printf before each output: fmt.Printf("\033[0;0H").

  • 写回答

1条回答 默认 最新

  • douxing6532 2019-05-13 06:13
    关注

    You can use the ANSI Escape Codes

    First, save the position of the cursor with fmt.Print("\033[s"), then for each line, restore the position and clear the line before printing the line with fmt.Print("\033[u\033[K")

    Your code could be:

    // before entering the loop
    fmt.Print("\033[s") // save the cursor position
    
    for ... {
        ...
        fmt.Print("\033[u\033[K") // restore the cursor position and clear the line
        if err != nil {
            fmt.Printf("Could not retrieve file info for %s
    ", f)
        } else {
            fmt.Printf("Retrieved %s
    ", f)
        }
        ...
    }
    

    It should work unless your program prints the line at the bottom of the screen, generating a scrolling of your text. In this case, you should remove the and make sure that no line exceeds the screen (or window) width.

    Another option could be to move the cursor up after each write:

    for ... {
        ...
        fmt.Print("\033[G\033[K") // move the cursor left and clear the line
        if err != nil {
            fmt.Printf("Could not retrieve file info for %s
    ", f)
        } else {
            fmt.Printf("Retrieved %s
    ", f)
        }
        fmt.Print("\033[A") // move the cursor up
        ...
    }
    

    Again, this works as long as your line fits on the screen/window width.

    评论

报告相同问题?

悬赏问题

  • ¥15 镍氢电池充电器设计实物使用原理
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号