mpb是一个在终端进行进度条渲染的工具库
package mainimport ("math/rand""time""github.com/vbauerster/mpb/v8""github.com/vbauerster/mpb/v8/decor"
)func main() {// initialize progress container, with custom widthp := mpb.New(mpb.WithWidth(64))total := 100name := "Single Bar:"// create a single bar, which will inherit container's widthbar := p.New(int64(total),// BarFillerBuilder with custom stylempb.BarStyle().Lbound("╢").Filler("▌").Tip("▌").Padding("░").Rbound("╟"),mpb.PrependDecorators(// display our name with one space on the rightdecor.Name(name, decor.WC{W: len(name) + 1, C: decor.DidentRight}),// replace ETA decorator with "done" message, OnComplete eventdecor.OnComplete(decor.AverageETA(decor.ET_STYLE_GO, decor.WC{W: 4}), "done",),),mpb.AppendDecorators(decor.Percentage()),)// simulating some workmax := 100 * time.Millisecondfor i := 0; i < total; i++ {time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)bar.Increment()}// wait for our bar to complete and flushp.Wait()
}
执行结果:

var wg sync.WaitGroup// passed wg will be accounted at p.Wait() callp := mpb.New(mpb.WithWaitGroup(&wg))total, numBars := 100, 3wg.Add(numBars)for i := 0; i < numBars; i++ {name := fmt.Sprintf("Bar#%d:", i)bar := p.AddBar(int64(total),mpb.PrependDecorators(// simple name decoratordecor.Name(name),// decor.DSyncWidth bit enables column width synchronizationdecor.Percentage(decor.WCSyncSpace),),mpb.AppendDecorators(// replace ETA decorator with "done" message, OnComplete eventdecor.OnComplete(// ETA decorator with ewma age of 60decor.EwmaETA(decor.ET_STYLE_GO, 60, decor.WCSyncWidth), "done",),),)// simulating some workgo func() {defer wg.Done()rng := rand.New(rand.NewSource(time.Now().UnixNano()))max := 100 * time.Millisecondfor i := 0; i < total; i++ {// start variable is solely for EWMA calculation// EWMA's unit of measure is an iteration's durationstart := time.Now()time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10)// we need to call EwmaIncrement to fulfill ewma decorator's contractbar.EwmaIncrement(time.Since(start))}}()}// wait for passed wg and for all bars to complete and flushp.Wait()
运行结果:

参考地址: https://github.com/vbauerster/mpb
上一篇:咏能组什么成语