API Reference

The following section outlines mybar’s Python API.

mybar.run()

If you’re using Python and just want a continuous status bar printed to your screen, this function does the trick. It reads the default config file to determine its options.

mybar.run(*, once: bool = False, file: PathLike = None) None

Generate a new Bar from a config file and run it in STDOUT. Ask to write the file if it doesn’t exist.

Parameters:
  • once (bool) – Print the bar only once, defaults to False

  • file (PathLike) – The config file to source, defaults to CONFIG_FILE

Fields

Fields are at the core of mybar. They are responsible for generating specific, meaningful, dynamic text at every iteration of a bar’s lifespan.

class mybar.Field

Continuously generate and format one bit of information in a Bar.

Pre-defined default Fields can be looked up by name using Field.from_default().

Parameters:
  • name (str) – A unique identifier for the new Field, defaults to func.__name__

  • func (FieldFunc) – The Python function to run at every interval if no constant_output is set

  • icon (Icon | Sequence`[ASCII_Icon, Unicode_Icon]) – The Field icon (or a sequence of one for ASCII terminals and one for terminals that support Unicode fonts) positioned in front of Field contents or in place of {icon} in template, if provided, defaults to ''

  • template (FormatStr) –

    A curly-brace format string. This parameter is required if icon is None.

    Valid placeholders:
    • {icon} references icon

    • {} references Field contents

    Example:
    When the Field’s current contents are '69F' and its icon is 'TEMP',
    template='[{icon}]: {}' shows as '[TEMP]: 69F'

  • interval (float) – How often in seconds Field contents are updated, defaults to 1.0

  • clock_align (bool) – Update contents at the start of each second, defaults to False

  • timely (bool) – Run func as soon as possible after every refresh, defaults to False

  • overrides_refresh (bool) – Ensure updates to this Field re-print the Bar between refreshes, defaults to False

  • threaded (bool) – Run this Field in a separate thread, defaults to False

  • always_show_icon (bool) – Show icons even when contents are empty, defaults to False

  • run_once (bool) – Permanently set contents by running func only once, defaults to False

  • constant_output (str, optional) – Permanently set contents instead of running a function

  • bar (Bar, optional) – Attach the Field to this Bar

  • args (Args, optional) – Positional args passed to func

  • kwargs (Kwargs, optional) – Keyword args passed to func

  • setup (FieldFuncSetup, optional) – A special callback that updates kwargs with static data that func would otherwise have to evaluate every time it runs

  • command (str) – A shell command to run

  • script (PathLike) – The path to a shell script to run

  • allow_multiline (bool) – Don’t join the output of a command or script if it spans multiple lines, defaults to False

Raises:

errors.IncompatibleArgsError when neither func nor constant_output are given

Raises:

errors.IncompatibleArgsError when neither icon nor template are given

Raises:

TypeError when func is not callable

Raises:

TypeError when setup, if given, is not callable

classmethod from_default(name: str, *, overrides: FieldSpec = {}, source: Mapping[FieldName, FieldSpec] = None, fmt_sig: FormatStr = None) Self

Quickly get a default Field and customize its parameters.

Parameters:
  • name (str) – Name of the default Field to access or customize

  • overrides (namespaces.FieldSpec, optional) – Custom parameters that override those of the default Field

  • source (Mapping[FieldName, namespaces.FieldSpec]) – The dict in which to look up default fields, defaults to Field._default_fields

Returns:

A new Field

Return type:

Field

Raises:

errors.DefaultFieldNotFoundError when source does not contain name

classmethod from_format_string(fmt: FormatStr) Self

Get a Field from a curly-brace field in a format string.

Parameters:

fmt (:class`FormatStr`) – The format string to convert

property icon: str

The field icon as determined by the output stream of its bar. It defaults to the TTY icon (self._icon[1]) if no bar is set.

async run(bar: Bar, once: bool) None

Run an async Field callback and send its output to a status bar.

Parameters:
  • bar (Bar) – Send results to this status bar

  • once (bool) – Run the Field function once

run_threaded(bar: Bar, once: bool) None

Run a blocking Field func and send its output to a status bar.

Parameters:
  • bar (Bar) – Send results to this status bar

  • once (bool) – Run the Field function once

make_thread(bar: Bar, run_once: bool) None

Return a thread that runs the Field’s callback.

Parameters:
  • bar (Bar) – Send results to this status bar

  • once (bool) – Run the Field function once

Bars

Bars control how mybar renders text and orchestrate all the parts that make that happen.

class mybar.Bar

Create highly customizable status bars.

Parameters:
  • fields (Iterable[FieldPrecursor]) – An iterable of default field names or Field instances, defaults to None

  • template (FormatStr) – A curly-brace format string with field names, defaults to None

  • separator (Separator | Sequence[ASCII_Separator, Unicode_Separator], optional) – The field separator string when fields is given, or a sequence of 2 of these, defaults to '|' The first string is used in terminal environments where only ASCII is supported. The second string is used in graphical environments where support for Unicode is more likely. This enables the same Bar instance to use the most optimal separator automatically.

  • refresh (float) – How often in seconds the bar automatically prints itself, defaults to 1.0

  • count (int | None) – Only print the bar this many times, or never stop when None, defaults to None

  • break_lines (bool) – Print each refresh after a newline character ('\n'), defaults to False

  • clock_align (bool) – Whether to synchronize redraws at the start of each new second (updates to the clock are shown accurately), defaults to True

  • join_empty_fields (bool) – Whether to draw separators around fields with no content, defaults to False

  • override_cooldown (float) – Cooldown in seconds between handling sequential field overrides, defaults to 1/60. A longer cooldown typically means less flickering.

  • thread_cooldown (float) – How long a field thread loop sleeps after checking if the bar is still running, defaults to 1/8. Between executions, unlike async fields, a threaded field sleeps for several iterations of thread_cooldown seconds that always add up to Field.interval seconds. Between sleeps, it checks if the bar has stopped. A shorter cooldown means more chances to check if the bar has stopped and a faster exit time.

  • unicode (bool) – Use Unicode variants of separator and Field icons, if given; optional

  • stream (IO) – The bar’s output stream, defaults to sys.stdout

Raises:

errors.InvalidOutputStreamError when stream does not implement the IO protocol

Raises:

errors.IncompatibleArgsError when neither template nor fields are given

Raises:

errors.IncompatibleArgsError when template is None but no separator is given

Raises:

TypeError when fields is not iterable, or when template is not a string

property config: BarConfig

The BarConfig used to instantiate the Bar, if applicable.

property file: PathLike

The config file used to instantiate the Bar, if applicable.

classmethod from_config(config: BarConfig, *, overrides: BarSpec = {}, ignore_with: Pattern | tuple[Pattern] | None = '//') Self

Return a new Bar from a BarConfig or a dict of Bar parameters. Ignore keys and list elements starting with ignore_with, which is '//' by default. If :param ignore_with: is None, do not remove any values.

Parameters:
  • config (Mapping) – The Mapping to convert

  • overrides (namespaces.BarSpec) – Replace items in config with these params, defaults to {}

  • ignore_with (Pattern | tuple[Pattern] | None, optional) – A pattern to ignore, defaults to '//'

Returns:

A new Bar

Return type:

Bar

Raises:

errors.IncompatibleArgsError when no field_order is defined or when no template is defined

Raises:

errors.DefaultFieldNotFoundError when either a field in field_order or a field in template cannot be found in Field._default_fields

Raises:

errors.UndefinedFieldError when a custom field name in field_order or a custom field name in template is not properly defined in field_definitions

Raises:

errors.InvalidFieldSpecError when a field definition is not of the form namespaces.FieldSpec

Note

config can be a regular Mapping as long as it matches the form of namespaces.BarSpec.

classmethod from_file(file: PathLike = None, overrides: BarSpec = {}) Self

Generate a new Bar by reading a config file.

Parameters:
Returns:

A new Bar

Return type:

Bar

property clearline_char: ConsoleControlCode

A special character printed to TTY streams between refreshes. Its purpose is to clear characters left behind by longer lines.

property fields: tuple[Field]

A tuple of the bar’s Field objects.

property in_a_tty: bool

True if the bar was run from a terminal, otherwise False.

property running: bool

True if the bar is currently running, otherwise False.

property separator: Separator

The field separator as determined by the output stream. Defaults to the TTY sep (self._separators[0]) if no stream is set.

append(field: FieldPrecursor) Self

Append a new Field to the bar.

field will be converted to Field, appended to the field list and joined to the end of the bar. If Bar.template is defined, it will override the new field order.

Parameters:

field (FieldPrecursor) – The field to append

Returns:

The modified bar

Return type:

Bar

extend(fields: Iterable[FieldPrecursor]) Self

Append several new Fields to the bar. Field precursors in fields will be converted to Field, appended to the field list and joined to the end of the bar. If Bar.template is defined, it will override the new field order. the fields are displayed.

Parameters:

fields (Iterable[FieldPrecursor]) – The fields to append

Returns:

The modified bar

Return type:

Bar

run(once: bool = None, stream: IO = None, *, bg: bool = False) None

Run the bar in the specified output stream. Block until an exception is raised and exit smoothly.

Parameters:
  • stream (IO) – The IO stream in which to run the bar, defaults to Bar._stream

  • once (bool) – Run the bar only once, defaults to internal state

  • bg (bool) – (Not fully implemented) Run the bar in the background without printing, defaults to False This is used for Bar.line_generator() and for testing.

Returns:

None

Note

This method cannot be called within an async event loop.

line_generator() Iterator

Return a generator yielding status lines. This requires running the Fields in a separate thread, which has yet to be implemented.

current_line() Line

Return the most recently printed line.

Field Functions

Field Functions are evaluated at each interval to create content for Fields.

async mybar.field_funcs.get_battery_info(fmt: FormatStr = '{pct:02.0f}{state}', *args, **kwargs) Contents

Battery capacity as a percent and whether or not it is charging.

Parameters:

fmt (FormatStr) –

A curly-brace format string with two optional named fields:
  • pct: Current battery percent as a float

  • state: Whether or not the battery is charging

Defaults to "{pct:02.0f}{state}"

mybar.field_funcs.get_cpu_temp(fmt: str = '{temp:02.0f}{scale}', in_fahrenheit=False, *args, **kwargs) Contents

Current CPU temperature in Celcius or Fahrenheit.

Parameters:
  • fmt (FormatStr) –

    A curly-brace format string with two optional named fields:
    • temp: Current CPU temperature as a float

    • scale: 'C' or 'F', depending on in_fahrenheit

    Defaults to "{temp:02.0f}{scale}"

  • in_fahrenheit (bool) – Display the temperature in Fahrenheit instead of Celcius, defaults to False

mybar.field_funcs.get_cpu_usage(fmt: FormatStr = '{:02.0f}%', interval: float = None, *args, **kwargs) Contents

System CPU usage in percent over a specified interval.

Parameters:
  • fmt (FormatStr) – A curly-brace format string with one positional field, defaults to "{:02.0f}%"

  • interval (float, optional) – Time to block before returning a result. Only set this in a threaded Field.

mybar.field_funcs.get_datetime(fmt: str = '%Y-%m-%d %H:%M:%S', *args, **kwargs) Contents

Current time as formatted with fmt.

Parameters:

fmt (str) – A format string with %-based format codes used by datetime.strftime(), defaults to "%Y-%m-%d %H:%M:%S"

async mybar.field_funcs.get_disk_usage(fmt: FormatStr = '{free:.1f}{unit}', path: PathLike = '/', unit: MetricSymbol = 'G', *args, **kwargs) Contents

Disk usage of a partition at a given path.

Parameters:
  • fmt (FormatStr) –

    A curly-brace format string with five optional named fields:
    • unit: The same value as unit

    • total: Total disk partition size

    • used: Used disk space

    • free: Free disk space (total - used)

    • percent: Percent of total disk space that is used (used / total, a float)

    Defaults to "{free:.1f}{unit}"

  • path (os.PathLike) – The path to a directory or file on a disk partition, defaults to '/'

  • unit (MetricSymbol) – The unit prefix symbol, defaults to 'G'

Raises:

errors.InvalidArgError if unit is not a valid MetricSymbol

mybar.field_funcs.get_host(fmt: FormatStr = '{nodename}', *args, **kwargs) Contents

System host information using os.uname().

Parameters:

fmt (FormatStr) –

A curly-brace format string with five optional named fields:
  • nodename: System hostname

  • sysname: Operating system kernel name

  • release: Kernel release

  • version: Kernel version

  • machine: Machine architecture

Defaults to "{nodename}"

mybar.field_funcs.get_hostname(*args, **kwargs) Contents

System hostname.

mybar.field_funcs.get_mem_usage(fmt: FormatStr = '{used:.1f}{unit}', unit: MetricSymbol = 'G', *args, **kwargs) Contents

System memory usage.

Parameters:
  • fmt (FormatStr) –

    A curly-brace format string with the following optional named fields:
    • unit: The same value as unit

    • available: Available memory

    • total: Total physical memory excluding swap

    • used: Memory in use

    • percent: Percent memory usage calculated as (total - available) / total * 100

    Defaults to "{free:.1f}{unit}" See the psutil documentation for all possible optional named fields.

  • unit (MetricSymbol) – The unit prefix symbol, defaults to 'G'

Raises:

errors.InvalidArgError if unit is not a valid MetricSymbol

async mybar.field_funcs.get_net_stats(fmt: FormatStr = '{name}', nm: bool = True, nm_filt: NmConnFilterSpec = None, default: str = '', *args, **kwargs) Contents

Active network info from either NetworkManager or iwconfig.

Parameters:
  • fmt (FormatStr) –

    A curly-brace format string with five optional named fields:
    • name: The connection name

    • uuid: The connection uuid

    • type: The connection type

    • device: The connection device

    Defaults to "{name}"

  • nm (bool) – Use NetworkManager, defaults to True

  • nm_filt (NmConnFilterSpec, optional) – Filter from active NetworkManager connections

  • default (str) – The string to replace fmt fields when there is no active connection.

async mybar.field_funcs.get_uptime(fmt: FormatStr, dynamic: bool = True, sep: str = ':', setupvars=None, *args, **kwargs) Contents

System uptime.

This function does some neat things. When dynamic is True, the format string is split into groups using sep. If any format string fields in a group evaluate to 0, the whole group is hidden.

For example, using the format string "{days}d:{hours}h:{mins}m", 86580 seconds is represented as 1d:0h:3m when dynamic is False, but would be shortened to 1d:3m when dynamic is True.

Using only one unit, like "{hours}", will round hours to an integer by default. If floating point values are desired, a format spec must be used: "{hours:.4f}"

Format specs can be used to great effect, like in all other Field functions which accept fmt: "{hours:_^10.4f}"

Parameters:
  • fmt (FormatStr) – A curly-brace format string with seven optional named fields: secs, mins, hours, days, weeks, months, and years

  • dynamic (bool) – Given sep, automatically hide groups of units when they are 0, defaults to True

  • sep (str) – Delimits groups of format fields to be hidden/shown together, defaults to ":"

Containing Configs

The configuration of a mybar.Bar can be stored in a BarConfig, a subclass of dict. This class also defines methods for making new configs from files and the command line as well as for writing preexisting configs out to files.

class mybar.BarConfig

Bases: dict

Build and transport configs between files, dicts and command lines.

Parameters:

Note

options and defaults must be Mapping instances of form namespaces.BarConfigSpec

classmethod from_file(file: PathLike = None, *, defaults: BarConfigSpec = None, overrides: BarConfigSpec = {}) BarConfig

Return a new BarConfig from a config file path.

Parameters:
Returns:

A new BarConfig instance

Return type:

BarConfig

Raises:

OSError for issues with accessing the file

classmethod validate() bool | Never

Check if the config file has errors.

write_with_approval(file: PathLike = None) bool

Write a config file to file. Prompt the user for approval before writing.

Parameters:

file (PathLike) – Write to this file, defaults to CONFIG_FILE

Returns:

True if the file was written, False if not

as_scuff() ScuffText

Return a BarConfig as a string with Scuff formatting.

as_json(indent: int = 4) JSONText

Return a BarConfig as a string with JSON formatting.

Parameters:

indent (int) – How many spaces to indent by, defaults to 4

Command Line Tools

Use these tools to gather and prompt for data from the command line.

class mybar.cli.ArgParser

A custom command line parser used by the command line utility.

parse_args(args: list[str] = None) tuple[BarConfigSpec, _CmdOptionSpec]

Parse command line arguments and return a dict of options. This will additionally process args with key-value pairs. If args is None, process from STDIN.

Parameters:

args (list[str]) – The args to parse, get from STDIN by default

process_assignment_args(opts: BarConfigSpec, dest_map: dict[OptName, OptName | tuple[OptName]] = None) BarConfigSpec

Make dicts from key-value pairs in assignment args. Split strings on ‘=’ and convert the resultant keys and values to dicts.

['foo=bar', 'baz=grok'] -> {'foo': 'bar', 'baz': 'grok'}

Parameters:
  • opts (BarConfigSpec) – The Bar options dict

  • dest_map (dict[OptName, OptName | tuple[OptName]]) – A dict mapping dest names to names of new dict items in which to save key-value pairs, defaults to Parser.assignment_arg_map

static process_field_options(options: Iterable[AssignmentOption]) dict[FieldName, FieldConfigSpec]

Parse variable assignment args given for Field definitions. Each option in options should look like ‘key=val’. We specifically handle Field options. To that end, parse nested options with emulated dotted attribute access by ignoring all options not of the form ‘field.key=val’. After parsing options, return a dict mapping them to Field names, similar to field_definitions in Bar.from_config().

I think this has some logical chinks. Definitely overengineered.

Parameters:

options (Iterable[AssignmentOption]) – Assignment option ‘key=val’ pairs to parse

Returns:

a dict mapping Field names to dicts of options

Return type:

dict[FieldName, FieldConfigSpec]

add_arguments() None

Equip the parser with all its arguments.

quit(message: str = 'Exiting...') Never

Print a message and exit the program.

class mybar.cli.OptionsAsker

A tool for presenting options and gathering user input.

Parameters:
  • opts (OptSpec) – A mapping of options

  • default (str) – The default option name

  • question (str) – Give the user context, defaults to ""

  • case_sensitive (bool) – Options are case-sensitive, defaults to False

  • highlight_method (HighlightMethod) – How to differentiate the default option

Raises:

ValueError if default is not a key in opts

gen_optstrings(highlight_method: HighlightMethod | None = HighlightMethod.CAPITALIZE) tuple[OptName]

A tuple of option names with the default highlighted.

Parameters:

highlight_method (HighlightMethod) – How the default option should be differentiated, defaults to HighlightMethod.CAPITALIZE

Returns:

A tuple of option names

Return type:

tuple[OptName]

ask(prompt: str = None, repeat_prompt: bool = True) Any

Show a prompt and get user input for an option. Block until a valid option is given.

Parameters:
  • prompt (string, optional) – Shows possible option names for the user to input

  • repeat_prompt (bool) – Repeat the whole prompt if the user enters an invalid option, defaults to True Setting this to False is useful if OptionsAsker.question is very long.

Returns:

The option value chosen by the user

Return type:

Any

Constants

mybar defines the following constant values.

mybar.constants.CONFIG_FILE: str = '~/.config/mybar/mybar.conf'

The default mybar config file path.

mybar.constants.DEBUG: bool = False

The default debug state.

mybar.constants.CSI: ConsoleControlCode = '\x1b['

Unix terminal escape code (control sequence introducer).

mybar.constants.CLEAR_LINE: ConsoleControlCode = '\x1b[2K'

VT100 escape code to clear the line.

mybar.constants.HIDE_CURSOR: ConsoleControlCode = '?25l'

VT100 escape code to hide the cursor.

mybar.constants.UNHIDE_CURSOR: ConsoleControlCode = '?25h'

VT100 escape code to unhide the cursor.

String Formatting

Classes for parsing, structuring and manipulating text.

class mybar.formatting.FormatterFieldSig

Bases: NamedTuple

A NamedTuple representing a format replacement field as generated by Formatter().parse().

Parameters:
  • lit (FormatterLiteral) – Literal text preceding a replacement field

  • name (FormatterFname) – The name of such a field, found inside curly braces

  • spec (FormatterFormatSpec) – The field’s format spec, found inside curly braces

  • conv (FormatterConversion, optional) – The field’s conversion value, found inside curly braces

lit: FormatterLiteral

Alias for field number 0

name: FormatterFname

Alias for field number 1

spec: FormatterFormatSpec

Alias for field number 2

conv: FormatterConversion

Alias for field number 3

classmethod from_str(fmt: FormatStr) Self

Convert a replacement field to a tuple of its elements. If there are multiple fields in the format string, only process the first one.

Parameters:

fmt (FormatStr) – The format string to convert

as_string(with_literal: bool = True, with_conv: bool = True, with_spec: bool = True) FormatStr

Recreate a format string field from a single field signature.

Parameters:
  • with_literal (bool) – Include the signature’s FormatterLiteral, defaults to True

  • with_conv (bool) – Include the signature’s FormatterConversion, defaults to True

Returns:

The format string represented by the signature

Return type:

FormatStr

static __new__(_cls, lit: FormatterLiteral, name: FormatterFname, spec: FormatterFormatSpec, conv: FormatterConversion)

Create new instance of FormatterFieldSig(lit, name, spec, conv)

class mybar.formatting.FmtStrStructure

Bases: tuple[FormatterFieldSig]

Represents the structure of a whole format string broken up by the standard library’s string.Formatter.parse() into a tuple of FormatterFieldSig, one for each replacement field.

get_names() tuple[FormatterFname]

Return a tuple with all the format string’s field names in order. A positional field will have a name of ''.

validate_fields(valid_names: Iterable[FormatterFname] | None = None, check_positionals: bool = False, check_specs: bool = False) bool | NoReturn

Ensure the represented format string has valid replacement fields.

Parameters:
  • valid_names (Iterable[FormatterFname]) – Provide a collection of valid names to ensure that each field name refers to a valid Field object, defaults to None. Raise InvalidFormatStringFieldNameError for any fields with names not in valid_names. When valid_names is None, field names are not checked.

  • check_positionals (bool) – Ensure each field has a name, defaults to False. Raise MissingFieldnameError if any field is missing a field name.

  • check_specs (bool) – Ensure the format spec in each field is valid, defaults to False. Raise InvalidFormatStringFormatSpecError if any field has an invalid format spec.

Returns:

True if the format string passes these checks, and raises exceptions if not.

Return type:

bool | NoReturn

Raises:

errors.MissingFieldnameError when template contains positional fields

Raises:

InvalidFormatStringFieldNameError When valid_names is None, field names are not checked.

Raises:

errors.InvalidFormatStringFormatSpecError when template contains fields with invalid format specs

class mybar.formatting.ConditionalFormatStr

Bases: object

Reinterpret format strings based on the data they reference. Values in a mapping which are predicated False have their groupings shown blank when the mapping is formatted.

Parameters:
  • fmt (FormatStr) – The initial format string

  • sep – Surrounds related fields and literal text that should be grouped together, defaults to ":"

parse(sep: str = None) tuple[tuple[FormatterFname], FmtStrStructure]

Parse a format string using its format fields and a separator.

Parameters:

sep (str, optional) – Surrounds related fields and literal text that should be grouped together, defaults to self.sep

Returns:

A nested tuple of the string’s fieldnames and its FmtStrStructure

Return type:

tuple[tuple[:class:`FormatterFname], :class:`FmtStrStructure]

format(namespace: ~collections.abc.Mapping[FormatterFname, ~typing.Any], predicate: ~collections.abc.Callable[[~typing.Any], bool] = <class 'bool'>, sep: str = None, substitute: str = None, round_by_default: bool = True) str

Format a dict of numbers according to a format string by parsing fields delineated by a separator sep. Field groups which fail the predicate are not shown in the final output string. If specified, substitute will replace invalid fields instead.

Parameters:
  • namespace (Mapping`[:class:`FormatterFname]) – A mapping with values to which fieldnames refer

  • predicate (Callable[[Any], bool]) – A callable to determine whether a field should be printed, defaults to bool()

  • sep (str) – Used to join field groups into the final string, defaults to self.sep

  • substitute (str, optional) – When set, replaces a field group that fails predicate

  • round_by_default (bool) – Round values if they are floats, defaults to True

Returns:

A string with field groups hidden which don’t pass predicate

Return type:

str

class mybar.formatting.ElapsedTime

Bases: object

Represent elapsed time in seconds with a variety of larger units.

conversions_to_secs = {'years': 29030400, 'months': 2419200, 'weeks': 604800, 'days': 86400, 'hours': 3600, 'mins': 60, 'secs': 1}

A mapping of units of elapsed time to their equivalents in seconds.

classmethod in_desired_units(secs: int, units: Iterable[Duration]) dict[Duration, int]

Convert seconds to multiple units of time.

The resulting value of the smallest unit in units is kept as a float. Smaller units overflow into larger units when they meet or exceed the threshold given by ElapsedTime.conversions_to_secs[larger_unit], but only if a larger unit is present in units.

For example…

Running in_desired_units(12345, ('mins', 'hours'))

yields {'hours': 3, 'mins': 25.75},

but in_desired_units(12345, ('mins', 'days'))

yields {'days': 0, 'mins': 205.75},

and in_desired_units(12345, ('hours',))

yields {'hours': 3.4291666666666667}.

Parameters:
  • secs (int) – Seconds to be converted

  • units (Iterable`[:class:`Duration]) – Units to convert

Returns:

A mapping of unit names to amount of time in those units

Return type:

dict[Duration, int]

mybar.formatting.format_uptime(secs: int, sep: str, namespace: Mapping[Duration, int], groups: Iterable[Iterable[FormatterFieldSig]], *args, **kwargs) str

Format a dict of numbers according to a format string by parsing fields delineated by a separator.

Parameters:
  • secs (int) – Total elapsed time in seconds (unused)

  • sep (str) – A string that separates groups of text based on division of time

  • namespace (Mapping`[:class:`Unit, int]) – A mapping of time unit names to int

  • groups (Iterable`[:class:`Iterable`[:class:`FormatterFieldSig]]) – A format string broken up by _setups.setup_uptime() into tuples of FormatterFieldSig based on the locations of separator

Utilities

A miscellany of utility functions.

Utility functions

mybar.utils.join_options(it: Iterable[object], /, sep: str = ', ', final_sep: str = 'or', quote: bool = True, oxford: bool = True, limit: int = None, overflow: str = '...', metasep: str = ' ') str

Tie together a list of objects for use in natural sentences. Commonly used to present valid variable options or expected values in error messages.

Parameters:
  • it (Iterable[object]) – The iterable of objects to join

  • sep (str) – The string separating every option, defaults to ', '

  • final_sep (str) – The string separating the last two options, defaults to 'or'

  • quote (bool) – Put each option in quotes, defaults to True

  • oxford (bool) – Put sep between second-last option and final_sep, otherwise metasep, defualts to True

  • limit (int) – Show this many options before appending overflow, defaults to None

  • overflow – The string appended when limit options are joined, defaults to '...'

  • metasep (str) – Separates final_sep and the last option

mybar.utils.str_to_bool(value: str | bool, /) bool

Returns True or False bools for truthy or falsy strings.

mybar.utils.recursive_scrub(obj: Iterable, /, test: Callable[[Any], bool], inplace: bool = False) Iterable

Scrub an iterable of any elements that pass a callable predicate.

By default, return a scrubbed copy of the original object. For dicts, remove whole items whose keys pass the predicate. Remove elements recursively.

mybar.utils.scrub_comments(obj: Iterable, /, pattern: str | tuple[str] = '//', inplace: bool = False) Iterable

Scrub an iterable of any elements that begin with a substring.

By default, return a scrubbed copy of the original object. For dicts, remove whole items whose keys match the pattern. Remove elements recursively.

mybar.utils.make_error_message(cls: Exception, doing_what: str = None, blame: Any = None, expected: str = None, details: Iterable[str] = None, epilogue: str = None, file: str = None, line: int = None, indent: str = '  ', indent_level: int = 0) Exception

Dynamically build an error message from various bits of context.

Return an exception with the message passed as args.

mybar.utils.process_nested_dict(dct: dict | Any, roots: Sequence[str] = [], descended: int = 0) tuple[list[list[str]], list[PythonData]]

Unravel nested dicts into keys and assignment values.

Parameters:
  • dct (Mapping | Any) – The nested dict to process, or an inner value of it

  • roots (Sequence`[:class:`str], defaults to []) – The keys which surround the current dct

  • descended (int, defaults to 0) – How far dct is from the outermost key

Returns:

Attribute names and assignment values

mybar.utils.nested_update(orig: Mapping | Any, upd: Mapping) dict

Merge two dicts and properly give them their innermost values.

Parameters:
  • orig (dict | Any) – The original dict

  • upd (dict) – A dict that updates orig

Exceptions

A group of custom errors.

exception mybar.errors.BrokenFormatStringError

Bases: FormatStringError

Raised when a format string cannot be properly parsed or contains positional fields ('{}').

exception mybar.errors.CLIFatalError

Bases: Exception

Base class for errors that cause the CLI program to exit.

Parameters:

msg (str) – The error message to issue when exiting

exception mybar.errors.CLIUsageError

Bases: CLIFatalError

Raised when the CLI program is used incorrectly.

exception mybar.errors.CompatibilityWarning

Bases: Warning

Raised when certain application features will break if used in an environment without proper support.

exception mybar.errors.DefaultFieldNotFoundError

Bases: LookupError

Raised for references to an undefined default Field.

exception mybar.errors.FailedSetup

Bases: Exception

Raised by a setup function when it cannot return a suitable value. Field.run() uses backup for the Bar buffer value instead.

Parameters:

backup (str) – The field contents to use instead of the setup function return value

exception mybar.errors.FormatStringError

Bases: ValueError

Base class for exceptions involving format strings.

exception mybar.errors.IncompatibleArgsError

Bases: ValueError

Raised when a class is instantiated with one or more missing or incompatible parameters.

exception mybar.errors.InvalidArgError

Bases: ValueError

Raised by a field function when it receives an invalid argument.

exception mybar.errors.InvalidBarError

Bases: AttributeError

Raised when Field._check_bar() finds missing attributes in a potential status bar.

exception mybar.errors.InvalidFieldError

Bases: TypeError

Raised when a field is either not an instance of Field or a string not found in the default fields container.

exception mybar.errors.InvalidFieldSpecError

Bases: TypeError

Raised when an expected FieldSpec has the wrong type or an invalid structure.

exception mybar.errors.InvalidFormatStringFieldNameError

Bases: FormatStringError

Raised when a format string has a field name not allowed or not defined by kwargs in a str.format() call.

exception mybar.errors.InvalidOutputStreamError

Bases: AttributeError

Raised when an IO stream lacks write(), flush() and isatty() methods.

exception mybar.errors.MissingFieldnameError

Bases: FormatStringError

Raised when a format string field lacks a fieldname (i.e. is positional) when one is expected.

classmethod with_highlighting(sigs: FmtStrStructure, epilogue: str = '') Self

Make an error message with highlighting under positional fields.

Parameters:
  • sigs (FmtStrStructure) – The problematic format string in the form of a FmtStrStructure

  • epilogue (str) – A message at the end of the traceback

Returns:

A new errors.MissingFieldnameError

Return type:

errors.MissingFieldnameError

exception mybar.errors.UndefinedFieldError

Bases: LookupError

Raised if, when parsing a config file, a field name appears in the field_order item of the dict passed to Bar.from_dict() that is neither found in its field_definitions parameter nor in Field._default_fields.

Custom Types

A horde of descriptive type aliases and custom data structures.

class docs._custom_types.ASCII_Icon

alias of str

class docs._custom_types.ASCII_Separator

alias of str

class docs._custom_types.Args

alias of list

class docs._custom_types.AssignmentOption

alias of Pattern[(?P<key>w+)=(?P<val>.*)]

class docs._custom_types.ConsoleControlCode

alias of str

class docs._custom_types.Contents

alias of str

class docs._custom_types.Duration

Possible names for units of elapsed time.

alias of Literal[‘secs’, ‘mins’, ‘hours’, ‘days’, ‘weeks’, ‘months’, ‘years’]

class docs._custom_types.FieldFuncSetup

alias of Callable[[P], P.kwargs]

class docs._custom_types.FieldFunc

alias of Callable[[P], str]

class docs._custom_types.FieldName

alias of str

class docs._custom_types.FieldOrder

alias of tuple[FieldName]

class docs._custom_types.FieldPrecursor

alias of FieldName | Field | FormatterFieldSig

class docs._custom_types.FileContents

alias of str

class docs._custom_types.FormatStr

alias of str

class docs._custom_types.FormatterConversion

The conversion part of one tuple in the iterable returned by string.Formatter.parse().

alias of str | None

class docs._custom_types.FormatterFname

The field_name part of one tuple in the iterable returned by string.Formatter.parse().

alias of str | None

class docs._custom_types.FormatterFormatSpec

The format_spec part of one tuple in the iterable returned by string.Formatter.parse().

alias of str | None

class docs._custom_types.FormatterLiteral

The literal_text part of one tuple in the iterable returned by string.Formatter.parse().

alias of str | None

class docs._custom_types.Icon

alias of str

class docs._custom_types.JSONText

alias of str

class docs._custom_types.Kwargs

alias of dict

class docs._custom_types.MetricSymbol

alias of Literal[‘K’, ‘M’, ‘G’, ‘T’, ‘P’]

class docs._custom_types.NmConnIDSpecifier

One of several keywords NetworkManager provides to narrow down connection results. From the nmcli man page:

id, uuid, path and apath keywords can be used if ID is
ambiguous. Optional ID-specifying keywords are:

id
    the ID denotes a connection name.

uuid
    the ID denotes a connection UUID.

path
    the ID denotes a D-Bus static connection path in the format of
    /org/freedesktop/NetworkManager/Settings/num or just num.

apath
    the ID denotes a D-Bus active connection path in the format of
    /org/freedesktop/NetworkManager/ActiveConnection/num or just num.

alias of Literal[‘id’, ‘uuid’, ‘path’, ‘apath’]

class docs._custom_types.NmConnFilterSpec

A mapping passed to mybar.field_funcs.get_net_stats() to filter multiple connections.

alias of Mapping[NmConnIDSpecifier, str]

class docs._custom_types.OptName

alias of str

class docs._custom_types.OptSpec

alias of dict[OptName, Any]

class docs._custom_types.Pattern

alias of str

class docs._custom_types.PythonData

alias of object

class docs._custom_types.Separator

alias of str

class docs._custom_types.StorageMeasure

alias of Literal[‘total’, ‘used’, ‘free’, ‘percent’]

class docs._custom_types.Unicode_Icon

alias of str

class docs._custom_types.Unicode_Separator

alias of str

class mybar.namespaces.FieldSpec

Bases: FieldConfigSpec

A dict specifying the structure of mybar.Field constructor parameters.

func: Callable[[P], str]
setup: ~P]
bar: Bar
unserializable = ('func', 'setup', 'bar')
name: FieldName
icon: Icon | Sequence[ASCII_Icon, Unicode_Icon]
template: FormatStr
interval: float
clock_align: bool
overrides_refresh: bool
threaded: bool
always_show_icon: bool
run_once: bool
constant_output: str
args: Args
kwargs: Kwargs
command: str
script: PathLike
allow_multiline: bool
class mybar.namespaces.BarSpec

Bases: TypedDict

A dict specifying the structure of mybar.Bar constructor parameters.

break_lines: bool
clock_align: bool
count: int
debug: bool
join_empty_fields: bool
override_cooldown: float
refresh: float
run_once: bool
thread_cooldown: float
unicode: bool

The following field params are mutually exclusive with template:

fields: Iterable[Field | FieldName]
field_order: Sequence[FieldName]
separator: Separator | Sequence[ASCII_Separator, Unicode_Separator]

The template param is mutually exclusive with all field params:

template: FormatStr
class mybar.namespaces.BarConfigSpec

Bases: BarSpec

Specify options for mybar.bar.BarConfig and config files.

debug: bool
field_definitions: Mapping[FieldName, FieldSpec]
field_icons: Mapping[FieldName, Sequence[ASCII_Icon, Unicode_Icon] | Icon]
field_order: Iterable[FieldName]
from_icons: Mapping[FieldName, Icon]
break_lines: bool
clock_align: bool
count: int
join_empty_fields: bool
override_cooldown: float
refresh: float
run_once: bool
thread_cooldown: float
unicode: bool
fields: Iterable[Field | FieldName]
separator: Separator | Sequence[ASCII_Separator, Unicode_Separator]
template: FormatStr