pb

package
v8.0.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2017 License: MIT, BSD-3-Clause Imports: 9 Imported by: 0

README

Terminal progress bar for Go

Simple progress bar for console programs.

Installation

go get github.com/cheggaaa/pb

Usage

package main

import (
	"github.com/cheggaaa/pb"
	"time"
)

func main() {
	count := 100000
	bar := pb.StartNew(count)
	for i := 0; i < count; i++ {
		bar.Increment()
		time.Sleep(time.Millisecond)
	}
	bar.FinishPrint("The End!")
}

Result will be like this:

> go run test.go
37158 / 100000 [================>_______________________________] 37.16% 1m11s

Customization

// create bar
bar := pb.New(count)

// refresh info every second (default 200ms)
bar.SetRefreshRate(time.Second)

// show percents (by default already true)
bar.ShowPercent = true

// show bar (by default already true)
bar.ShowBar = true

// no counters
bar.ShowCounters = false

// show "time left"
bar.ShowTimeLeft = true

// show average speed
bar.ShowSpeed = true

// sets the width of the progress bar
bar.SetWidth(80)

// sets the width of the progress bar, but if terminal size smaller will be ignored
bar.SetMaxWidth(80)

// convert output to readable format (like KB, MB)
bar.SetUnits(pb.U_BYTES)

// and start
bar.Start()

Progress bar for IO Operations

// create and start bar
bar := pb.New(myDataLen).SetUnits(pb.U_BYTES)
bar.Start()

// my io.Reader
r := myReader

// my io.Writer
w := myWriter

// create proxy reader
reader := bar.NewProxyReader(r)

// and copy from pb reader
io.Copy(w, reader)

// create and start bar
bar := pb.New(myDataLen).SetUnits(pb.U_BYTES)
bar.Start()

// my io.Reader
r := myReader

// my io.Writer
w := myWriter

// create multi writer
writer := io.MultiWriter(w, bar)

// and copy
io.Copy(writer, r)

Custom Progress Bar Look-and-feel

bar.Format("<.- >")

Multiple Progress Bars (experimental and unstable)

#####Multiple bars do not works at Windows!!!

Do not print to terminal while pool is active.

package main

import (
    "math/rand"
    "github.com/cheggaaa/pb"    
    "sync"
    "time"
)

// create bars
first := pb.New(200).Prefix("First ")
second := pb.New(200).Prefix("Second ")
third := pb.New(200).Prefix("Third ")
// start pool
pool, err := pb.StartPool(first, second, third)
if err != nil {
	panic(err)
}
// update bars
wg := new(sync.WaitGroup)
for _, bar := range []*pb.ProgressBar{first, second, third} {
	wg.Add(1)
	go func(cb *pb.ProgressBar) {
		for n := 0; n < 200; n++ {
			cb.Increment()
			time.Sleep(time.Millisecond * time.Duration(rand.Intn(100)))
		}
		cb.Finish()
		wg.Done()
	}(bar)
}
wg.Wait()
// close pool
pool.Stop()

The result will be as follows:

$ go run example/multiple.go 
First 141 / 1000 [===============>---------------------------------------] 14.10 % 44s
Second 139 / 1000 [==============>---------------------------------------] 13.90 % 44s
Third 152 / 1000 [================>--------------------------------------] 15.20 % 40s

Documentation

Overview

Simple console progress bars

Index

Constants

View Source
const (
	// AverageMetricAge average over a one-minute period, which means the average
	// age of the metrics is in the period of 30 seconds
	AverageMetricAge float64 = 30.0

	// Decay formula for computing the decay factor for average metric age
	Decay float64 = 2 / (float64(AverageMetricAge) + 1)
)
View Source
const (
	// Default refresh rate - 200ms
	DEFAULT_REFRESH_RATE = time.Millisecond * 200
	FORMAT               = "[=>-]"
)

Variables

This section is empty.

Functions

func Format

func Format(i int64, units Units, width int) string

Format integer

func FormatBytes

func FormatBytes(i int64) (result string)

Convert bytes to human readable string. Like a 2 MB, 64.2 KB, 52 B

func FormatDuration

func FormatDuration(d time.Duration) string

Types

type Callback

type Callback func(out string)

Callback for custom output For example:

bar.Callback = func(s string) {
    mySuperPrint(s)
}

type EWMA

type EWMA struct {
	// contains filtered or unexported fields
}

EWMA represents the exponentially weighted moving average of a series of numbers.

func (*EWMA) Add

func (e *EWMA) Add(value float64)

Add a value to the series and update the moving average.

func (*EWMA) Value

func (e *EWMA) Value() float64

Value returns the current value of the moving average.

type ProgressBar

type ProgressBar struct {
	Total                            int64
	RefreshRate                      time.Duration
	ShowPercent, ShowCounters        bool
	ShowSpeed, ShowTimeLeft, ShowBar bool
	ShowFinalTime                    bool
	Output                           io.Writer
	Callback                         Callback
	NotPrint                         bool
	Units                            Units
	Width                            int
	ForceWidth                       bool
	ManualUpdate                     bool

	TimeLeft   time.Duration
	TotalBytes int64

	// default width for unit numbers and time box
	UnitsWidth   int
	TimeBoxWidth int
	BarWidth     int

	BarStart string
	BarEnd   string
	Empty    string
	Current  string
	CurrentN string

	AlwaysUpdate bool
	// contains filtered or unexported fields
}

func New

func New(total int) *ProgressBar

Create new progress bar object

func New64

func New64(total int64) *ProgressBar

Create new progress bar object uding int64 as total

func StartNew

func StartNew(total int) *ProgressBar

Create new object and start

func (*ProgressBar) CurrentValue

func (pb *ProgressBar) CurrentValue() int64

func (*ProgressBar) Finish

func (pb *ProgressBar) Finish()

End print

func (*ProgressBar) Format

func (pb *ProgressBar) Format(format string) *ProgressBar

Set custom format for bar Example: bar.Format("[=>_]") Example: bar.Format("[\x00=\x00>\x00-\x00]") // \x00 is the delimiter

func (*ProgressBar) GOString

func (pb *ProgressBar) GOString() string

func (*ProgressBar) GetWidth

func (pb *ProgressBar) GetWidth() int

func (*ProgressBar) Postfix

func (pb *ProgressBar) Postfix(postfix string) *ProgressBar

Set postfix string

func (*ProgressBar) Prefix

func (pb *ProgressBar) Prefix(prefix string) *ProgressBar

Set prefix string

func (*ProgressBar) Set64

func (pb *ProgressBar) Set64(current int64) *ProgressBar

Set64 sets the current value as int64

func (*ProgressBar) SetMaxWidth

func (pb *ProgressBar) SetMaxWidth(width int) *ProgressBar

Set max width, if width is bigger than terminal width, will be ignored

func (*ProgressBar) SetRefreshRate

func (pb *ProgressBar) SetRefreshRate(rate time.Duration) *ProgressBar

Set bar refresh rate

func (*ProgressBar) SetScale

func (pb *ProgressBar) SetScale(scale float64) *ProgressBar

func (*ProgressBar) SetUnits

func (pb *ProgressBar) SetUnits(units Units) *ProgressBar

Set units bar.SetUnits(U_NO) - by default bar.SetUnits(U_BYTES) - for Mb, Kb, etc

func (*ProgressBar) SetWidth

func (pb *ProgressBar) SetWidth(width int) *ProgressBar

Set bar width

func (*ProgressBar) Start

func (pb *ProgressBar) Start() *ProgressBar

Start print

func (*ProgressBar) Update

func (pb *ProgressBar) Update()

Write the current state of the progressbar

type Units

type Units int
const (
	// By default, without type handle
	U_NO Units = iota
	// Handle as b, Kb, Mb, etc
	U_BYTES
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL