Is it possible to change the existing printline dynamically in golang?

1,211 views
Skip to first unread message

Zhaoxun Yan

unread,
Apr 1, 2022, 1:38:37 AM4/1/22
to golang-nuts
I just noticed how python pip upgraded from printing numerous process bars like this:
■■■                   30% completed
■■■■                 40% completed
■■■■■■            60% completed
■■■■■■■■       80% completed
■■■■■■■■■■  100% completed

to a single line of a growing bar and changing declaration.

It is definitely a functionality that  prompts of both Linux and Windows allows -
To change the previous print line.
Is it possible to realize this in golang?

  Zhaoxun

Henry

unread,
Apr 1, 2022, 3:34:08 AM4/1/22
to golang-nuts
You can use the ansi escape code if the target terminal supports it. Alternatively, you can use the carriage return '\r' and reprint the line. Note you may need to overwrite with empty space to delete the line before rewriting it.

Zhaoxun Yan

unread,
Apr 1, 2022, 8:12:11 AM4/1/22
to golang-nuts
Got it:

package main

import(
    "fmt"
    "time"
    )

func main() {
  fmt.Printf("Hello")
  time.Sleep(time.Second)
  time.Sleep(time.Second)
  fmt.Printf("\r")
  fmt.Printf("World\n")
}

Amnon

unread,
Apr 1, 2022, 9:25:14 AM4/1/22
to golang-nuts
Yes, this is the murky world of ANSI escape codes.
Fortunately there are a whole load of libraries which do this for you...
Try https://github.com/cheggaaa/pb
or https://github.com/schollz/progressbar
or github.com/vardius/progress-go

Zhaoxun Yan

unread,
Apr 11, 2022, 11:07:27 PM4/11/22
to golang-nuts
Thanks a log Amnon! :D
Reply all
Reply to author
Forward
0 new messages