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
Barfrom 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 toFalsefile (
PathLike) – The config file to source, defaults toCONFIG_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 seticon (
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 to1.0clock_align (
bool) – Update contents at the start of each second, defaults toFalsetimely (
bool) – Run func as soon as possible after every refresh, defaults toFalseoverrides_refresh (
bool) – Ensure updates to this Field re-print the Bar between refreshes, defaults toFalsethreaded (
bool) – Run this Field in a separate thread, defaults toFalsealways_show_icon (
bool) – Show icons even when contents are empty, defaults toFalserun_once (
bool) – Permanently set contents by running func only once, defaults toFalseconstant_output (
str, optional) – Permanently set contents instead of running a functionargs (
Args, optional) – Positional args passed to funckwargs (
Kwargs, optional) – Keyword args passed to funcsetup (
FieldFuncSetup, optional) – A special callback that updates kwargs with static data that func would otherwise have to evaluate every time it runscommand (
str) – A shell command to runscript (
PathLike) – The path to a shell script to runallow_multiline (
bool) – Don’t join the output of a command or script if it spans multiple lines, defaults toFalse
- Raises:
errors.IncompatibleArgsErrorwhen neither func nor constant_output are given- Raises:
errors.IncompatibleArgsErrorwhen neither icon nor template are given- Raises:
TypeErrorwhen func is not callable- Raises:
TypeErrorwhen 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 defaultFieldto access or customizeoverrides (
namespaces.FieldSpec, optional) – Custom parameters that override those of the default Fieldsource (
Mapping[FieldName, namespaces.FieldSpec]) – Thedictin which to look up default fields, defaults toField._default_fields
- Returns:
A new
Field- Return type:
- Raises:
errors.DefaultFieldNotFoundErrorwhen source does not contain name
- classmethod from_format_string(fmt: FormatStr) Self
Get a
Fieldfrom 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
Fieldcallback and send its output to a status bar.- Parameters:
bar (
Bar) – Send results to this status baronce (
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 orFieldinstances, defaults toNonetemplate (
FormatStr) – A curly-brace format string with field names, defaults toNoneseparator (
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 sameBarinstance to use the most optimal separator automatically.refresh (
float) – How often in seconds the bar automatically prints itself, defaults to1.0count (
int|None) – Only print the bar this many times, or never stop whenNone, defaults toNonebreak_lines (
bool) – Print each refresh after a newline character ('\n'), defaults to Falseclock_align (
bool) – Whether to synchronize redraws at the start of each new second (updates to the clock are shown accurately), defaults toTruejoin_empty_fields (
bool) – Whether to draw separators around fields with no content, defaults toFalseoverride_cooldown (
float) – Cooldown in seconds between handling sequential field overrides, defaults to1/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 to1/8. Between executions, unlike async fields, a threaded field sleeps for several iterations of thread_cooldown seconds that always add up toField.intervalseconds. 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; optionalstream (
IO) – The bar’s output stream, defaults tosys.stdout
- Raises:
errors.InvalidOutputStreamErrorwhen stream does not implement the IO protocol- Raises:
errors.IncompatibleArgsErrorwhen neither template nor fields are given- Raises:
errors.IncompatibleArgsErrorwhen template isNonebut no separator is given- Raises:
TypeErrorwhen fields is not iterable, or when template is not a string
- 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
Barfrom aBarConfigor a dict ofBarparameters. Ignore keys and list elements starting with ignore_with, which is'//'by default. If :param ignore_with: isNone, do not remove any values.- Parameters:
config (
Mapping) – TheMappingto convertoverrides (
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:
- Raises:
errors.IncompatibleArgsErrorwhen no field_order is defined or when no template is defined- Raises:
errors.DefaultFieldNotFoundErrorwhen either a field in field_order or a field in template cannot be found inField._default_fields- Raises:
errors.UndefinedFieldErrorwhen a custom field name in field_order or a custom field name in template is not properly defined in field_definitions- Raises:
errors.InvalidFieldSpecErrorwhen a field definition is not of the formnamespaces.FieldSpec
Note
config can be a regular
Mappingas long as it matches the form ofnamespaces.BarSpec.
- classmethod from_file(file: PathLike = None, overrides: BarSpec = {}) Self
Generate a new
Barby reading a config file.- Parameters:
file (
PathLike) – The config file to read, defaults toconstants.CONFIG_FILEoverrides (
namespaces.BarSpec) – Replace items in config with these params, defaults to{}
- Returns:
A new
Bar- Return type:
- 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 in_a_tty: bool
Trueif the bar was run from a terminal, otherwiseFalse.
- property running: bool
Trueif the bar is currently running, otherwiseFalse.
- 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. IfBar.templateis defined, it will override the new field order.- Parameters:
field (
FieldPrecursor) – The field to append- Returns:
The modified bar
- Return type:
- 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. IfBar.templateis 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:
- 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 toBar._streamonce (
bool) – Run the bar only once, defaults to internal statebg (
bool) – (Not fully implemented) Run the bar in the background without printing, defaults toFalseThis is used forBar.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 afloatstate: 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 afloatscale:'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 toFalse
- 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 threadedField.
- 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 bydatetime.strftime(), defaults to"%Y-%m-%d %H:%M:%S"
See also
- 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 unittotal: Total disk partition sizeused: Used disk spacefree: Free disk space (total - used)percent: Percent of total disk space that is used (used / total, afloat)
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.InvalidArgErrorif unit is not a validMetricSymbol
- 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 hostnamesysname: Operating system kernel namerelease: Kernel releaseversion: Kernel versionmachine: Machine architecture
Defaults to
"{nodename}"
- 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 unitavailable: Available memorytotal: Total physical memory excluding swapused: Memory in usepercent: 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.InvalidArgErrorif unit is not a validMetricSymbol
- 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 nameuuid: The connection uuidtype: The connection typedevice: The connection device
Defaults to
"{name}"nm (
bool) – Use NetworkManager, defaults toTruenm_filt (
NmConnFilterSpec, optional) – Filter from active NetworkManager connectionsdefault (
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 as1d:0h:3mwhen dynamic isFalse, but would be shortened to1d:3mwhen dynamic isTrue.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}"See also
The Python format spec mini language documentation
- Parameters:
fmt (
FormatStr) – A curly-brace format string with seven optional named fields:secs,mins,hours,days,weeks,months, andyearsdynamic (
bool) – Given sep, automatically hide groups of units when they are0, defaults toTruesep (
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:
dictBuild and transport configs between files, dicts and command lines.
- Parameters:
options (
namespaces.BarConfigSpec) – Optionalnamespaces.BarConfigSpecparameters that override those of defaultsdefaults (
Mapping) – Parameters to use by default, defaults toBar._default_params
Note
options and defaults must be
Mappinginstances of formnamespaces.BarConfigSpec- classmethod from_file(file: PathLike = None, *, defaults: BarConfigSpec = None, overrides: BarConfigSpec = {}) BarConfig
Return a new
BarConfigfrom a config file path.- Parameters:
file (
PathLike) – The filepath to the config file, defaults to'~/.mybar.json'defaults (
namespaces.BarConfigSpec) – The basenamespaces.BarConfigSpecdict whose params the newBarConfigwill override, defaults toBar._default_paramsoverrides (
namespaces.BarConfigSpec) – Additional param overrides to the config file
- Returns:
A new
BarConfiginstance- Return type:
- Raises:
OSErrorfor 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 toCONFIG_FILE- Returns:
Trueif the file was written,Falseif not
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 dictdest_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 toParser.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 optionsdefault (
str) – The default option namequestion (
str) – Give the user context, defaults to""case_sensitive (
bool) – Options are case-sensitive, defaults toFalsehighlight_method (
HighlightMethod) – How to differentiate the default option
- Raises:
ValueErrorif 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 toHighlightMethod.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 inputrepeat_prompt (
bool) – Repeat the whole prompt if the user enters an invalid option, defaults toTrueSetting this toFalseis useful ifOptionsAsker.questionis 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:
NamedTupleA NamedTuple representing a format replacement field as generated by Formatter().parse().
- Parameters:
lit (
FormatterLiteral) – Literal text preceding a replacement fieldname (
FormatterFname) – The name of such a field, found inside curly bracesspec (
FormatterFormatSpec) – The field’s format spec, found inside curly bracesconv (
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’sFormatterLiteral, defaults toTruewith_conv (
bool) – Include the signature’sFormatterConversion, defaults toTrue
- 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 validFieldobject, defaults to None. RaiseInvalidFormatStringFieldNameErrorfor any fields with names not in valid_names. When valid_names isNone, field names are not checked.check_positionals (
bool) – Ensure each field has a name, defaults toFalse. RaiseMissingFieldnameErrorif any field is missing a field name.check_specs (
bool) – Ensure the format spec in each field is valid, defaults toFalse. RaiseInvalidFormatStringFormatSpecErrorif any field has an invalid format spec.
- Returns:
Trueif the format string passes these checks, and raises exceptions if not.- Return type:
bool|NoReturn- Raises:
errors.MissingFieldnameErrorwhen template contains positional fields- Raises:
InvalidFormatStringFieldNameErrorWhen valid_names isNone, field names are not checked.- Raises:
errors.InvalidFormatStringFormatSpecErrorwhen template contains fields with invalid format specs
- class mybar.formatting.ConditionalFormatStr
Bases:
objectReinterpret format strings based on the data they reference. Values in a mapping which are predicated
Falsehave their groupings shown blank when the mapping is formatted.- Parameters:
fmt (
FormatStr) – The initial format stringsep – 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 toself.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 referpredicate (
Callable[[Any], bool]) – A callable to determine whether a field should be printed, defaults tobool()sep (
str) – Used to join field groups into the final string, defaults toself.sepsubstitute (
str, optional) – When set, replaces a field group that fails predicateround_by_default (
bool) – Round values if they are floats, defaults toTrue
- Returns:
A string with field groups hidden which don’t pass predicate
- Return type:
str
- class mybar.formatting.ElapsedTime
Bases:
objectRepresent 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 byElapsedTime.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 convertedunits (
Iterable`[:class:`Duration]) – Units to convert
- Returns:
A mapping of unit names to amount of time in those units
- Return type:
dict[Duration, int]
- Running
- 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 timenamespace (
Mapping`[:class:`Unit,int]) – A mapping of time unit names tointgroups (
Iterable`[:class:`Iterable`[:class:`FormatterFieldSig]]) – A format string broken up by_setups.setup_uptime()into tuples ofFormatterFieldSigbased 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 joinsep (
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 toTrueoxford (
bool) – Put sep between second-last option and final_sep, otherwise metasep, defualts toTruelimit (
int) – Show this many options before appending overflow, defaults toNoneoverflow – 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 itroots (
Sequence`[:class:`str], defaults to[]) – The keys which surround the current dctdescended (
int, defaults to0) – 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 dictupd (
dict) – A dict that updates orig
Exceptions
A group of custom errors.
- exception mybar.errors.BrokenFormatStringError
Bases:
FormatStringErrorRaised when a format string cannot be properly parsed or contains positional fields (
'{}').
- exception mybar.errors.CLIFatalError
Bases:
ExceptionBase 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:
CLIFatalErrorRaised when the CLI program is used incorrectly.
- exception mybar.errors.CompatibilityWarning
Bases:
WarningRaised when certain application features will break if used in an environment without proper support.
- exception mybar.errors.DefaultFieldNotFoundError
Bases:
LookupErrorRaised for references to an undefined default
Field.
- exception mybar.errors.FailedSetup
Bases:
ExceptionRaised by a setup function when it cannot return a suitable value.
Field.run()uses backup for theBarbuffer value instead.- Parameters:
backup (
str) – The field contents to use instead of the setup function return value
- exception mybar.errors.FormatStringError
Bases:
ValueErrorBase class for exceptions involving format strings.
- exception mybar.errors.IncompatibleArgsError
Bases:
ValueErrorRaised when a class is instantiated with one or more missing or incompatible parameters.
- exception mybar.errors.InvalidArgError
Bases:
ValueErrorRaised by a field function when it receives an invalid argument.
- exception mybar.errors.InvalidBarError
Bases:
AttributeErrorRaised when Field._check_bar() finds missing attributes in a potential status bar.
- exception mybar.errors.InvalidFieldError
Bases:
TypeErrorRaised when a field is either not an instance of
Fieldor a string not found in the default fields container.
- exception mybar.errors.InvalidFieldSpecError
Bases:
TypeErrorRaised when an expected
FieldSpechas the wrong type or an invalid structure.
- exception mybar.errors.InvalidFormatStringFieldNameError
Bases:
FormatStringErrorRaised 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:
AttributeErrorRaised when an
IOstream lackswrite(),flush()andisatty()methods.
- exception mybar.errors.MissingFieldnameError
Bases:
FormatStringErrorRaised 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 aFmtStrStructureepilogue (
str) – A message at the end of the traceback
- Returns:
A new
errors.MissingFieldnameError- Return type:
errors.MissingFieldnameError
- exception mybar.errors.UndefinedFieldError
Bases:
LookupErrorRaised if, when parsing a config file, a field name appears in the field_order item of the
dictpassed toBar.from_dict()that is neither found in its field_definitions parameter nor inField._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.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
nmcliman 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.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:
FieldConfigSpecA dict specifying the structure of
mybar.Fieldconstructor parameters.- func: Callable[[P], str]
- setup: ~P]
- bar: Bar
- unserializable = ('func', 'setup', 'bar')
- icon: Icon | Sequence[ASCII_Icon, Unicode_Icon]
- interval: float
- clock_align: bool
- overrides_refresh: bool
- threaded: bool
- always_show_icon: bool
- run_once: bool
- constant_output: str
- command: str
- script: PathLike
- allow_multiline: bool
- class mybar.namespaces.BarSpec
Bases:
TypedDictA dict specifying the structure of
mybar.Barconstructor 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:
- separator: Separator | Sequence[ASCII_Separator, Unicode_Separator]
The template param is mutually exclusive with all field params:
- class mybar.namespaces.BarConfigSpec
Bases:
BarSpecSpecify options for
mybar.bar.BarConfigand config files.- debug: bool
- field_icons: Mapping[FieldName, Sequence[ASCII_Icon, Unicode_Icon] | 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
- separator: Separator | Sequence[ASCII_Separator, Unicode_Separator]