API Reference
Classes
- class enlighten.Manager(stream=None, counter_class=Counter, **kwargs)
- Parameters
stream (file object) -- Output stream. If
None, defaults tosys.stdoutcounter_class (class) -- Progress bar class (Default:
Counter)set_scroll (bool) -- Enable scroll area redefinition (Default:
True)companion_stream (file object) -- See companion_stream below. (Default:
None)enabled (bool) -- Status (Default: True)
no_resize (bool) -- Disable resizing support
threaded (bool) -- When True resize handling is deferred until next write (Default: False unless multiple threads or multiple processes are detected)
kwargs (Dict[str, Any]) -- Any additional keyword arguments will be used as default values when
counter()is called.
Manager class for outputting progress bars to streams attached to TTYs
Progress bars are displayed at the bottom of the screen with standard output displayed above.
companion_stream
A companion stream is a file object that shares a TTY with the primary output stream. The cursor position in the companion stream will be moved in coordination with the primary stream.
If the value is
None,sys.stdoutandsys.stderrwill be used as companion streams. Unless explicitly specified, a stream which is not attached to a TTY (the case when redirected to a file), will not be used as a companion stream.- counter(position=None, **kwargs)
- Parameters
position (int) -- Line number counting from the bottom of the screen
autorefresh (bool) -- Refresh this counter when other bars are drawn
replace (
PrintableCounter) -- Replace given counter with new. Position ignored.kwargs (Dict[str, Any]) -- Any additional keyword arguments are passed to
Counter
- Returns
Instance of counter class
- Return type
Get a new progress bar instance
If
positionis specified, the counter's position will be pinned. AValueErrorwill be raised ifpositionexceeds the screen height or has already been pinned by another counter.If
autorefreshisTrue, this bar will be redrawn whenever another bar is drawn assuming it had beenmin_deltaseconds since the last update. This is usually unnecessary.Note
Counters are not automatically drawn when created because fields may be missing if subcounters are used. To force the counter to draw before updating, call
refresh().
- status_bar(*args, **kwargs)
- Parameters
position (int) -- Line number counting from the bottom of the screen
autorefresh (bool) -- Refresh this counter when other bars are drawn
replace (
PrintableCounter) -- Replace given counter with new. Position ignored.kwargs (Dict[str, Any]) -- Any additional keyword arguments are passed to
StatusBar
- Returns
Instance of status bar class
- Return type
Get a new status bar instance
If
positionis specified, the counter's position can change dynamically if additional counters are called without apositionargument.If
autorefreshisTrue, this bar will be redrawn whenever another bar is drawn assuming it had beenmin_deltaseconds since the last update. Generally, only need whenelapsedis used in status_format.
- stop()
Clean up and reset terminal
This method should be called when the manager and counters will no longer be needed.
Any progress bars that have
leaveset toTrueor have not been closed will remain on the console. All others will be cleared.Manager and all counters will be disabled.
- class enlighten.Counter(**kwargs)
- Parameters
bar_format (str) -- Progress bar format, see Format below
count (int) -- Initial count (Default: 0)
counter_format (str) -- Counter format, see Format below
color (str) -- Series color as a string or RGB tuple see Series Color
desc (str) -- Description
enabled (bool) -- Status (Default:
True)fill (str) -- Fill character used for
counter_format(Default: ' ')fields (dict) -- Additional fields used for formatting
leave (True) -- Leave progress bar after closing (Default:
True)manager (
Manager) -- Manager instance. Creates instance if not specified.min_delta (float) -- Minimum time, in seconds, between refreshes (Default: 0.1)
offset (int) -- Number of non-printable characters to account for when formatting
series (sequence) -- Progression series, see Series below
stream (file object) -- Output stream. Not used when instantiated through a manager
total (int) -- Total count when complete
unit (str) -- Unit label
Progress bar and counter class
A
Counterinstance can be created with theManager.counter()method or, when a standalone progress bar for simple applications is required, theCounterclass can be called directly. The output stream will default tosys.stdoutunlessstreamis set.Note
With the default values for
bar_formatandcounter_format,floatscan not be used fortotal,count, or provided toupdate(). In order to usefloats, provide custom formats tobar_formatandcounter_format. See Format below.Series
The progress bar is constructed from the characters in
series.seriesmust be a sequence (str,list,tuple) containing single characters.Default progress series (
series):' ▏▎▍▌▋▊▉█'The first character is the fill character. When the
countis 0, the bar will be made up of only this character. In the example below, characters 5 through 9 are fill characters.The last character is the full character. When the
countis equal tototal, the bar will be made up of only this character. In the example below, characters 0 through 3 are full characters.The remaining characters are fractional characters used to more accurately represent the transition between the full and fill characters. In the example below, character 4 is a fractional character.
'45% |████▋ |' '0123456789'
Series Color
The characters specified by
serieswill be displayed in the terminal's current foreground color. This can be overwritten with thecolorargument.colorcan be specified asNone, astringor, an iterable of three integers, 0 - 255, describing an RGB color.For backward compatibility, a color can be expressed as an integer 0 - 255, but this is deprecated in favor of named or RGB colors.
Compound colors, such as 'white_on_seagreen', 'bold_red', or 'underline_on_peru' are also supported.
If a terminal is not capable of 24-bit color, and is given a color outside of its range, the color will be downconverted to a supported color.
Valid colors for 8 color terminals:
black
blue
cyan
green
magenta
red
white
yellow
Additional colors for 16 color terminals:
bright_black
bright_blue
bright_cyan
bright_green
bright_magenta
bright_red
bright_white
bright_yellow
See this chart for a complete list of supported color strings.
Note
If an invalid color is specified, an
AttributeErrorwill be raisedFormat
If
totalisNoneorcountbecomes higher thantotal, the counter format will be used instead of the progress bar format.Default counter format (
counter_format):'{desc}{desc_pad}{count:d} {unit}{unit_pad}{elapsed}, {rate:.2f}{unit_pad}{unit}/s]{fill}' # Example output 'Loaded 30042 Files [00:01, 21446.45 Files/s] '
Default progress bar format (
bar_format):'{desc}{desc_pad}{percentage:3.0f}%|{bar}| {count:{len_total}d}/{total:d} [{elapsed}<{eta}, {rate:.2f}{unit_pad}{unit}/s]' # Example output 'Processing 22%|█████▊ | 23/101 [00:27<01:32, 0.84 Files/s]'
Available fields:
count(
int) - Current value ofcountdesc(
str) - Value ofdescdesc_pad(
str) - A single space ifdescis set, otherwise emptyelapsed(
str) - Time elapsed since instance was createdinterval(
float) - Average seconds per iteration (inverse of rate)rate(
float) - Average iterations per second since instance was createdunit(
str) - Value ofunitunit_pad(
str) - A single space ifunitis set, otherwise empty
Additional fields for
bar_formatonly:bar(
str) - Progress bar draw with characters fromserieseta(
str) - Estimated time to completionlen_total(
int) - Length oftotalwhen converted to a stringpercentage(
float) - Percentage completetotal(
int) - Value oftotal
Additional fields for
counter_formatonly:fill(
str) - Filled withfilluntil line is width of terminal. May be used multiple times. Minimum width is 3.
Additional fields when subcounters are used:
count_n (
int) - Current value ofcountcount_0(
int) - Remaining count after deducting counts for all subcounterscount_00 (
int) - Sum of counts from all subcounterspercentage_n (
float) - Percentage complete (bar_formatonly)percentage_0(
float) - Remaining percentage after deducting percentages for all subcounters (bar_formatonly)percentage_00 (
float) - Total of percentages from all subcounters
Note
n denotes the order the subcounter was added starting at 1. For example, count_1 is the count for the first subcounter added and count_2 is the count for the second subcounter added.
Additional fields when
add_subcounter()is called withall_fieldsset toTrue:eta_n (
str) - Estimated time to completion (bar_formatonly)interval_n(
float) - Average seconds per iteration (inverse of rate)rate_n (
float) - Average iterations per second since parent was created
User-defined fields:
Users can define fields in two ways, the
fieldsparameter and by passing keyword arguments toManager.counter()orCounter.update()The
fieldsparameter can be used to pass a dictionary of additional user-defined fields. The dictionary values can be updated after initialization to allow for dynamic fields. Any fields that share names with built-in fields are ignored.If fields are passed as keyword arguments to
Manager.counter()orCounter.update(), they take precedent over thefieldsparameter.Offset
When
offsetisNone, the width of the bar portion of the progress bar and the fill size for counter will be automatically determined, taking into account terminal escape sequences that may be included in the string.Under special circumstances, and to permit backward compatibility,
offsetmay be explicitly set to anintvalue. When explicitly set, automatic detection of escape sequences is disabled.Instance Attributes
- add_subcounter(color, count=0, all_fields=False)
- Parameters
color (str) -- Series color as a string or RGB tuple see Series Color
count (int) -- Initial count (Default: 0)
all_fields (bool) -- Populate
rate,interval, andetaformatting fields (Default: False)
- Returns
Subcounter instance
- Return type
Add a subcounter for multicolored progress bars
- clear(flush=True)
- Parameters
flush (bool) -- Flush stream after clearing bar (Default:True)
Clear bar
- close(clear=False)
Do final refresh and remove from manager
If
leaveis True, the default, the effect is the same asrefresh().
- property color
Color property
Preferred to be a string or iterable of three integers for RGB. Single integer supported for backwards compatibility
- property fill
Fill character used in formatting
- format(width=None, elapsed=None)
- Parameters
width (int) -- Width in columns to make progress bar
elapsed (float) -- Time since started. Automatically determined if
None
- Returns
Formatted progress bar or counter
- Return type
str
Format progress bar or counter
- refresh(flush=True, elapsed=None)
- Parameters
flush (bool) -- Flush stream after writing bar (Default:True)
elapsed (float) -- Time since started. Automatically determined if
None
Redraw bar
- property subcount
Sum of counts from all subcounters
- update(incr=1, force=False, **fields)
- Parameters
incr (int) -- Amount to increment
count(Default: 1)force (bool) -- Force refresh even if
min_deltahas not been reachedfields (dict) -- Fields for for formatting
Increment progress bar and redraw
Progress bar is only redrawn if
min_deltaseconds past since the last update
- class enlighten.StatusBar(*args, **kwargs)
- Parameters
enabled (bool) -- Status (Default:
True)color (str) -- Color as a string or RGB tuple see Status Color
fields (dict) -- Additional fields used for formating
fill (str) -- Fill character used in formatting and justifying text (Default: ' ')
justify (str) -- One of
Justify.CENTER,Justify.LEFT,Justify.RIGHTleave (True) -- Leave status bar after closing (Default:
True)min_delta (float) -- Minimum time, in seconds, between refreshes (Default: 0.1)
status_format (str) -- Status bar format, see Format
Status bar class
A
StatusBarinstance should be created with theManager.status_bar()method.Status Color
Color works similarly to color on
Counter, except it affects the entire status bar. See Series Color for more information.Format
There are two ways to populate the status bar, direct and formatted. Direct takes precedence over formatted.
Direct Status
Direct status is used when arguments are passed to
Manager.status_bar()orStatusBar.update(). Any arguments are coerced to strings and joined with a space. For example:status_bar.update('Hello', 'World!') # Example output: Hello World! status_bar.update('Hello World!') # Example output: Hello World! count = [1, 2, 3, 4] status_bar.update(*count) # Example output: 1 2 3 4
Formatted Status
Formatted status uses the format specified in the
status_formatparameter to populate the status bar.'Current Stage: {stage}' # Example output 'Current Stage: Testing'
Available fields:
elapsed(
str) - Time elapsed since instance was createdfill(
str) - Filled withfilluntil line is width of terminal. May be used multiple times. Minimum width is 3.
Note
The status bar is only updated when
StatusBar.update()orStatusBar.refresh()is called, so fields likeelapsedwill need additional calls to appear dynamic.User-defined fields:
Users can define fields in two ways, the
fieldsparameter and by passing keyword arguments toManager.status_bar()orStatusBar.update()The
fieldsparameter can be used to pass a dictionary of additional user-defined fields. The dictionary values can be updated after initialization to allow for dynamic fields. Any fields that share names with available fields are ignored.If fields are passed as keyword arguments to
Manager.status_bar()orStatusBar.update(), they take precedent over thefieldsparameter.Instance Attributes
- clear(flush=True)
- Parameters
flush (bool) -- Flush stream after clearing bar (Default:True)
Clear bar
- close(clear=False)
Do final refresh and remove from manager
If
leaveis True, the default, the effect is the same asrefresh().
- property color
Color property
Preferred to be a string or iterable of three integers for RGB. Single integer supported for backwards compatibility
- property fill
Fill character used in formatting
- format(width=None, elapsed=None)
- Parameters
width (int) -- Width in columns to make progress bar
elapsed (float) -- Time since started. Automatically determined if
None
- Returns
Formatted status bar
- Return type
str
Format status bar
- property justify
Maps to justify method determined by
justifyparameter
- refresh(flush=True, elapsed=None)
- Parameters
flush (bool) -- Flush stream after writing bar (Default:True)
elapsed (float) -- Time since started. Automatically determined if
None
Redraw bar
- update(*objects, **fields)
- Parameters
objects (list) -- Values for Direct Status
force (bool) -- Force refresh even if
min_deltahas not been reachedfields (dict) -- Fields for for Formatted Status
Update status and redraw
Status bar is only redrawn if
min_deltaseconds past since the last update
- class enlighten.SubCounter(parent, color=None, count=0, all_fields=False)
A child counter for multicolored progress bars.
This class tracks a portion of multicolored progress bar and should be initialized through
Counter.add_subcounter()Instance Attributes
- update(incr=1, force=False)
- Parameters
incr (int) -- Amount to increment
count(Default: 1)force (bool) -- Force refresh even if
min_deltahas not been reached
Increment progress bar and redraw
Both this counter and the parent are incremented.
Progress bar is only redrawn if min_delta seconds past since the last update on the parent.
- update_from(source, incr=1, force=False)
- Parameters
source (
SubCounter) --SubCounterorCounterto increment fromincr (int) -- Amount to increment
count(Default: 1)force (bool) -- Force refresh even if
min_deltahas not been reached
Move a value to this counter from another counter.
sourcemust be the parentCounterinstance or aSubCounterwith the same parent
Functions
- enlighten.get_manager(stream=None, counter_class=Counter, **kwargs)
- Parameters
stream (file object) -- Output stream. If
None, defaults tosys.stdoutcounter_class (class) -- Progress bar class (Default:
Counter)kwargs (Dict[str, Any]) -- Any additional keyword arguments will passed to the manager class.
- Returns
Manager instance
- Return type
Convenience function to get a manager instance
If
streamis not attached to a TTY, theManagerinstance is disabled.