core Package

core Package

class i3pystatus.core.CommandEndpoint(modules, io_handler_factory, io)[source]

Bases: object

Endpoint for i3bar click events:

  • modules – dict-like object with item access semantics via .get()
  • io_handler_factory – function creating a file-like object returning a JSON generator on .read()

Starts the background thread

class i3pystatus.core.Status(standalone=True, click_events=True, interval=1, input_stream=None, logfile=None, internet_check=None, keep_alive=False, logformat='%(asctime)s [%(levelname)-8s][%(name)s %(lineno)d] %(message)s', default_hints=None)[source]

Bases: object

The main class used for registering modules and managing I/O

  • standalone (bool) – Whether i3pystatus should read i3status-compatible input from input_stream.
  • interval (int) – Update interval in seconds.
  • input_stream – A file-like object that provides the input stream, if standalone is False.
  • click_events (bool) – Enable click events, if standalone is True.
  • logfile (str) – Path to log file that will be used by i3pystatus.
  • internet_check (tuple) – Address of server that will be used to check for internet connection by internet.
  • keep_alive – If True, modules that define the keep_alive flag will not be put to sleep when the status bar is hidden.
  • default_hints (dictionary) – Dictionary of default hints to apply to all modules. Can be overridden at a module level.
register(module, *args, **kwargs)[source]

Register a new module.

  • module – Either a string module name, or a module class, or a module instance (in which case args and kwargs are invalid).
  • kwargs – Settings for the module.

module instance


Run main loop.

color Module

class i3pystatus.core.color.ColorRangeModule[source]

Bases: object

Class to dynamically generate and select colors.

Requires the PyPI package colour

end_color = 'red'
get_gradient(value, colors, upper_limit=100)[source]

Map a value to a color :param value: Some value :return: A Hex color code

static get_hex_color_range(start_color, end_color, quantity)[source]

Generates a list of quantity Hex colors from start_color to end_color.

  • start_color – Hex or plain English color for start of range
  • end_color – Hex or plain English color for end of range
  • quantity – Number of colours to return

A list of Hex color values

static percentage(part, whole)[source]

Calculate percentage

start_color = '#00FF00'

command Module


alias of Result

i3pystatus.core.command.execute(command, detach=False)[source]

Runs a command in background. No output is retrieved. Useful for running GUI applications that would block click events.

  • command – A string or a list of strings containing the name and arguments of the program.
  • detach – If set to True the program will be executed using the i3-msg command. As a result the program is executed independent of i3pystatus as a child of i3 process. Because of how i3-msg parses its arguments the type of command is limited to string in this mode.
i3pystatus.core.command.run_through_shell(command, enable_shell=False)[source]

Retrieve output of a command. Returns a named tuple with three elements:

  • rc (integer) Return code of command.
  • out (string) Everything that was printed to stdout.
  • err (string) Everything that was printed to stderr.

Don’t use this function with programs that outputs lots of data since the output is saved in one variable.

  • command – A string or a list of strings containing the name and arguments of the program.
  • enable_shell – If set ot True users default shell will be invoked and given command to execute. The command should obviously be a string since shell does all the parsing.

desktop Module

class i3pystatus.core.desktop.BaseDesktopNotification(title, body, icon='dialog-information', urgency=1, timeout=-1, log_level=30)[source]

Bases: object

Class to display a desktop notification

  • title – Title of the notification
  • body – Body text of the notification, depending on the users system configuration HTML may be used, but is not recommended
  • icon – A XDG icon name, see
  • urgency – A value between 1 and 3 with 1 meaning low urgency and 3 high urgency.
  • timeout – Timeout in seconds for the notification. Zero means it needs to be dismissed by the user.

Display this notification

Returns:boolean indicating success
update(title=None, body=None, icon=None)[source]

Update this notification.


:return boolean indicating success

class i3pystatus.core.desktop.DesktopNotification(**kwargs)[source]

Bases: i3pystatus.core.desktop.DesktopNotification

URGENCY_LUT = (<Mock name='mock.Notify.Urgency.LOW' id='140611704974864'>, <Mock name='mock.Notify.Urgency.NORMAL' id='140611704975056'>, <Mock name='mock.Notify.Urgency.CRITICAL' id='140611704975120'>)
update(title=None, body=None, icon=None)[source]

exceptions Module

exception i3pystatus.core.exceptions.ConfigAmbigiousClassesError(module, *args, **kwargs)[source]

Bases: i3pystatus.core.exceptions.ConfigError

exception i3pystatus.core.exceptions.ConfigError(module, *args, **kwargs)[source]

Bases: Exception

ABC for configuration exceptions

format(*args, **kwargs)[source]
exception i3pystatus.core.exceptions.ConfigInvalidModuleError(module, *args, **kwargs)[source]

Bases: i3pystatus.core.exceptions.ConfigError

exception i3pystatus.core.exceptions.ConfigKeyError(module, *args, **kwargs)[source]

Bases: i3pystatus.core.exceptions.ConfigError, KeyError

exception i3pystatus.core.exceptions.ConfigMissingError(module, *args, **kwargs)[source]

Bases: i3pystatus.core.exceptions.ConfigError


imputil Module

class i3pystatus.core.imputil.ClassFinder(baseclass)[source]

Bases: object

Support class to find classes of specific bases in a module

instanciate_class_from_module(module, *args, **kwargs)[source]

io Module

class<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>, out=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Bases: object


Iterate over all input lines (Generator)


Interrupted respecting reader for stdin.

Raises EOFError if the end of stream has been reached


Unbuffered printing to stdout.

class, skiplines=2)[source]

Bases: object


Parse a single line of JSON and write modified JSON back.


Iterate over all JSON input (Generator)

class, modules, keep_alive, interval=1)[source]


I/O handler for standalone usage of i3pystatus (w/o i3status)

Writing works as usual, but reading will always return a empty JSON array, and the i3bar protocol header


Calling this method will send the status line to i3bar immediately without waiting for timeout (1s by default).


Current method is to compute average from all intervals.

n = -1
proto = [{'version': 1, 'click_events': True}, '[', '[]', ',[]']
refresh_signal_handler(signo, frame)[source]

This callback is called when SIGUSR1 signal is received.

It updates outputs of all modules by calling their run method.

Interval modules are updated in separate threads if their interval is above a certain treshold value. This treshold is computed by compute_treshold_interval() class method. The reasoning is that modules with larger intervals also usually take longer to refresh their output and that their output is not required in ‘real time’. This also prevents possible lag when updating all modules in a row.

suspend_signal_handler(signo, frame)[source]

By default, i3bar sends SIGSTOP to all children when it is not visible (for example, the screen sleeps or you enter full screen mode). This stops the i3pystatus process and all threads within it. For some modules, this is not desirable. Thankfully, the i3bar protocol supports setting the “stop_signal” and “cont_signal” key/value pairs in the header to allow sending a custom signal when these events occur.

Here we use SIGUSR2 for both “stop_signal” and “cont_signal” and maintain a toggle to determine whether we have just been stopped or continued. When we have been stopped, notify the IntervalModule managers that they should suspend any module that does not set the keep_alive flag to a truthy value, and when we have been continued, notify the IntervalModule managers that they can resume execution of all modules.

modules Module

class i3pystatus.core.modules.IntervalModule(*args, **kwargs)[source]

Bases: i3pystatus.core.modules.Module

interval = 5
managers = {}
required = set()

Called approximately every self.interval seconds

Do not rely on this being called from the same thread at all times. If you need to always have the same thread context, subclass AsyncModule.

settings = [('interval', 'interval in seconds between module updates'), ('on_leftclick', 'Callback called on left click (see :ref:`callbacks`)'), ('on_middleclick', 'Callback called on middle click (see :ref:`callbacks`)'), ('on_rightclick', 'Callback called on right click (see :ref:`callbacks`)'), ('on_upscroll', 'Callback called on scrolling up (see :ref:`callbacks`)'), ('on_downscroll', 'Callback called on scrolling down (see :ref:`callbacks`)'), ('on_doubleleftclick', 'Callback called on double left click (see :ref:`callbacks`)'), ('on_doublemiddleclick', 'Callback called on double middle click (see :ref:`callbacks`)'), ('on_doublerightclick', 'Callback called on double right click (see :ref:`callbacks`)'), ('on_doubleupscroll', 'Callback called on double scroll up (see :ref:`callbacks`)'), ('on_doubledownscroll', 'Callback called on double scroll down (see :ref:`callbacks`)'), ('on_otherclick', 'Callback called on other click (see :ref:`callbacks`)'), ('on_doubleotherclick', 'Callback called on double other click (see :ref:`callbacks`)'), ('on_change', 'Callback called when output is changed (see :ref:`callbacks`)'), ('multi_click_timeout', 'Time (in seconds) before a single click is executed.'), ('hints', 'Additional output blocks for module output (see :ref:`hints`)'), ('log_level', 'Set to true to log error to .i3pystatus-<pid> file.')]
class i3pystatus.core.modules.Module(*args, **kwargs)[source]

Bases: i3pystatus.core.settings.SettingsBase

hints = {'markup': 'none'}
multi_click_timeout = 0.25
on_change = None
on_click(button, **kwargs)[source]

Maps a click event with its associated callback.

Currently implemented events are:

Event Callback setting Button ID
Left click on_leftclick 1
Middle click on_middleclick 2
Right click on_rightclick 3
Scroll up on_upscroll 4
Scroll down on_downscroll 5
Others on_otherclick > 5

The action is determined by the nature (type and value) of the callback setting in the following order:

  1. If null callback (None), no action is taken.
  2. If it’s a python function, call it and pass any additional arguments.
  3. If it’s name of a member method of current module (string), call it and pass any additional arguments.
  4. If the name does not match with member method name execute program with such name.

See also

Callbacks for more information about callback settings and examples.

  • button – The ID of button event received from i3bar.
  • kwargs – Further information received from i3bar like the positions of the mouse where the click occurred.

Returns True if a valid callback action was executed. False otherwise.

on_doubledownscroll = None
on_doubleleftclick = None
on_doublemiddleclick = None
on_doubleotherclick = None
on_doublerightclick = None
on_doubleupscroll = None
on_downscroll = None
on_leftclick = None
on_middleclick = None
on_otherclick = None
on_rightclick = None
on_upscroll = None
position = 0

Called when this module is registered with a status handler

required = set()

Send a status update with the current module output

settings = [('on_leftclick', 'Callback called on left click (see :ref:`callbacks`)'), ('on_middleclick', 'Callback called on middle click (see :ref:`callbacks`)'), ('on_rightclick', 'Callback called on right click (see :ref:`callbacks`)'), ('on_upscroll', 'Callback called on scrolling up (see :ref:`callbacks`)'), ('on_downscroll', 'Callback called on scrolling down (see :ref:`callbacks`)'), ('on_doubleleftclick', 'Callback called on double left click (see :ref:`callbacks`)'), ('on_doublemiddleclick', 'Callback called on double middle click (see :ref:`callbacks`)'), ('on_doublerightclick', 'Callback called on double right click (see :ref:`callbacks`)'), ('on_doubleupscroll', 'Callback called on double scroll up (see :ref:`callbacks`)'), ('on_doubledownscroll', 'Callback called on double scroll down (see :ref:`callbacks`)'), ('on_otherclick', 'Callback called on other click (see :ref:`callbacks`)'), ('on_doubleotherclick', 'Callback called on double other click (see :ref:`callbacks`)'), ('on_change', 'Callback called when output is changed (see :ref:`callbacks`)'), ('multi_click_timeout', 'Time (in seconds) before a single click is executed.'), ('hints', 'Additional output blocks for module output (see :ref:`hints`)'), ('log_level', 'Set to true to log error to .i3pystatus-<pid> file.')]

Replaces all ampersands in full_text and short_text attributes of self.output with &amp;.

It is called internally when pango markup is used.

Can be called multiple times (&amp; won’t change to &amp;amp;).

i3pystatus.core.modules.is_method_of(method, object)[source]

Decide whether method is contained within the MRO of object.

settings Module

class i3pystatus.core.settings.SettingsBase(*args, **kwargs)[source]

Bases: object

Support class for providing a nice and flexible settings interface

Classes inherit from this class and define what settings they provide and which are required.

The constructor is either passed a dictionary containing these settings, or keyword arguments specifying the same.

Settings are stored as attributes of self.

static flatten_settings(settings)[source]

Attempt to retrieve protected settings from keyring if they are not already set.

get_setting_from_keyring(setting_identifier, keyring_backend=None)[source]

Retrieves a protected setting from keyring :param setting_identifier: must be in the format package.module.Class.setting


Convenience method which is called after all settings are set

In case you don’t want to type that super()…blabla :-)

log_level = 30
logger = None
required = set()

required can list settings which are required

settings = [('log_level', 'Set to true to log error to .i3pystatus-<pid> file.')]

settings should be tuple containing two types of elements:

  • bare strings, which must be valid Python identifiers.
  • two-tuples, the first element being a identifier (as above) and the second a docstring for the particular setting
class i3pystatus.core.settings.SettingsBaseMeta(name, bases, namespace)[source]

Bases: type

Add interval setting to settings attribute if it does not exist.

static get_merged_settings()[source]

threading Module

class i3pystatus.core.threading.ExceptionWrapper(workload)[source]

Bases: i3pystatus.core.threading.Wrapper

class i3pystatus.core.threading.Manager(target_interval)[source]

Bases: object

class i3pystatus.core.threading.Thread(target_interval, workloads=None, start_barrier=1)[source]

Bases: threading.Thread

branch(vtime, bound)[source]

If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy value. See the docs on the suspend_signal_handler method of the io module for more information.

class i3pystatus.core.threading.WorkloadWrapper(workload)[source]

Bases: i3pystatus.core.threading.Wrapper

time = 0.0
class i3pystatus.core.threading.Wrapper(workload)[source]

Bases: object


Obtain the module from it’s wrapper.

util Module

class i3pystatus.core.util.KeyConstraintDict(valid_keys, required_keys)[source]

Bases: collections.UserDict

A dict implementation with sets of valid and required keys

  • valid_keys – Set of valid keys
  • required_keys – Set of required keys, must be a subset of valid_keys
exception MissingKeys(keys)[source]

Bases: Exception


Returns a set of keys that are required but not set

class i3pystatus.core.util.ModuleList(status_handler, class_finder)[source]

Bases: collections.UserList

append(module, *args, **kwargs)[source]
class i3pystatus.core.util.MultiClickHandler(callback_handler, timeout)[source]

Bases: object

set_timer(button, cb, **kwargs)[source]
class i3pystatus.core.util.TimeWrapper(seconds, default_format='%m:%S')[source]

Bases: object

A wrapper that implements __format__ and __bool__ for time differences and time spans.

  • seconds – seconds (numeric)
  • default_format – the default format to be used if no explicit format_spec is passed to __format__

Format string syntax:

  • %h, %m and %s are the hours, minutes and seconds without leading zeros (i.e. 0 to 59 for minutes and seconds)
  • %H, %M and %S are padded with a leading zero to two digits, i.e. 00 to 59
  • %l and %L produce hours non-padded and padded but only if hours is not zero. If the hours are zero it produces an empty string.
  • %% produces a literal %
  • %E (only valid on beginning of the string) if the time is null, don’t format anything but rather produce an empty string. If the time is non-null it is removed from the string.

The formatted string is stripped, i.e. spaces on both ends of the result are removed

class TimeTemplate(template)[source]

Bases: string.Template

delimiter = '%'
idpattern = '[a-zA-Z]'
pattern = re.compile('\n %(?:\n (?P<escaped>%) | # Escape sequence of two delimiters\n (?P<named>[a-zA-Z]) | # delimiter and a Python identifier\n {(?P<braced>[a-zA-Z])} | # delimiter and a b, re.IGNORECASE|re.VERBOSE)
i3pystatus.core.util.convert_position(pos, json)[source]

Flattens a hierarchy of nested lists into a single list containing all elements in order

Parameters:l – list of arbitrary types and lists
Returns:list of arbitrary types
i3pystatus.core.util.formatp(string, **kwargs)[source]

Function for advanced format strings with partial formatting

This function consumes format strings with groups enclosed in brackets. A group enclosed in brackets will only become part of the result if all fields inside the group evaluate True in boolean contexts.

Groups can be nested. The fields in a nested group do not count as fields in the enclosing group, i.e. the enclosing group will evaluate to an empty string even if a nested group would be eligible for formatting. Nesting is thus equivalent to a logical or of all enclosing groups with the enclosed group.

Escaped brackets, i.e. \[ and \] are copied verbatim to output.

  • string – Format string
  • kwargs – keyword arguments providing data for the format string

Formatted string


Function decorator for retrieving the self argument from the stack.

Intended for use with callbacks that need access to a modules variables, for example:

from i3pystatus import Status, get_module
from i3pystatus.core.command import execute
status = Status(...)
# other modules etc.
def display_ip_verbose(module):
    execute('sh -c "ip addr show dev {dev} | xmessage -file -"'.format(dev=module.interface))
status.register("network", interface="wlan1", on_leftclick=display_ip_verbose)
class i3pystatus.core.util.internet[source]

Bases: object

Checks for internet connection by connecting to a server.

This class exposes two configuration variables:
  • address - a tuple containing (host,port) of the server to connect to
  • check_frequency - the frequency in seconds for checking the connection
Return type:bool

See also


address = ('', 80)
static check(res)[source]
static check_connection()[source]
check_frequency = 1
connected = False
dns_cache = []
last_checked = 3507.119835706
static resolve()[source]
i3pystatus.core.util.lchop(string, prefix)[source]

Removes a prefix from string

  • string – String, possibly prefixed with prefix
  • prefix – Prefix to remove from string

string without the prefix


Draws a bar made of unicode box characters.

Parameters:percentage – A value between 0 and 100
Returns:Bar as a string
i3pystatus.core.util.make_glyph(number, glyphs=' _▁▂▃▄▅▆▇█', lower_bound=0, upper_bound=100, enable_boundary_glyphs=False)[source]

Returns a single glyph from the list of glyphs provided relative to where the number is in the range (by default a percentage value is expected).

This can be used to create an icon based representation of a value with an arbitrary number of glyphs (e.g. 4 different battery status glyphs for battery percentage level).

  • number – The number being represented. By default a percentage value between 0 and 100 (but any range can be defined with lower_bound and upper_bound).
  • glyphs – Either a string of glyphs, or an array of strings. Using an array of strings allows for additional pango formatting to be applied such that different colors could be shown for each glyph).
  • lower_bound – A custom lower bound value for the range.
  • upper_bound – A custom upper bound value for the range.
  • enable_boundary_glyphs – Whether the first and last glyphs should be used for the special case of the number being <= lower_bound or >= upper_bound respectively.

The glyph found to represent the number

i3pystatus.core.util.make_graph(values, lower_limit=0.0, upper_limit=100.0, style='blocks')[source]

Draws a graph made of unicode characters.

  • values – An array of values to graph.
  • lower_limit – Minimum value for the y axis (or None for dynamic).
  • upper_limit – Maximum value for the y axis (or None for dynamic).
  • style – Drawing style (‘blocks’, ‘braille-fill’, ‘braille-peak’, or ‘braille-snake’).

Bar as a string

i3pystatus.core.util.make_vertical_bar(percentage, width=1, glyphs=None)[source]

Draws a vertical bar made of unicode characters.

  • percentage – A value between 0 and 100
  • width – How many characters wide the bar should be.

Bar as a String

i3pystatus.core.util.partition(iterable, limit, key=<function <lambda>>)[source]
i3pystatus.core.util.popwhile(predicate, iterable)[source]

Generator function yielding items of iterable while predicate holds for each item

  • predicate – function taking an item returning bool
  • iterable – iterable

iterable (generator function)


Decorator factory for methods requiring a predicate. If the predicate is not fulfilled during a method call, the method call is skipped and None is returned.

Parameters:predicate – A callable returning a truth value
Returns:Method decorator

See also


i3pystatus.core.util.round_dict(dic, places)[source]

Rounds all values in a dict containing only numeric types to places decimal places. If places is None, round to INT.


Open the specified paramater in the web browser if a URL is detected, othewrise pass the paramater to the shell as a subprocess. This function is inteded to bu used in on_leftclick/on_rightclick callbacks.

Parameters:url_or_command – String containing URL or command