core Package

core Package

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

Bases: object

Endpoint for i3bar click events: http://i3wm.org/docs/i3bar-protocol.html#_click_events

Parameters:
  • 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()
start()[source]

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

Parameters:
  • 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.

Parameters:
  • 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.
Returns:

module instance

run()[source]

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.

Parameters:
  • 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
Returns:

A list of Hex color values

static percentage(part, whole)[source]

Calculate percentage

start_color = '#00FF00'

command Module

i3pystatus.core.command.CommandResult

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.

Parameters:
  • 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.

Parameters:
  • 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

Parameters:
  • 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 http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
  • 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()[source]

Display this notification

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

Update this notification.

Parameters:

: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='140206259411880'>, <Mock name='mock.Notify.Urgency.NORMAL' id='140206259412272'>, <Mock name='mock.Notify.Urgency.CRITICAL' id='140206259412552'>)
display()[source]
update(title=None, body=None, icon=None)[source]

exceptions Module

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

Bases: i3pystatus.core.exceptions.ConfigError

format(ambigious_classes)[source]
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

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

Bases: i3pystatus.core.exceptions.ConfigError, KeyError

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

Bases: i3pystatus.core.exceptions.ConfigError

format(missing)[source]

imputil Module

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

Bases: object

Support class to find classes of specific bases in a module

get_class(module)[source]
get_matching_classes(module)[source]
get_module(module)[source]
instanciate_class_from_module(module, *args, **kwargs)[source]
predicate_factory(module)[source]

io Module

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

Bases: object

read()[source]

Iterate over all input lines (Generator)

read_line()[source]

Interrupted respecting reader for stdin.

Raises EOFError if the end of stream has been reached

write_line(message)[source]

Unbuffered printing to stdout.

class i3pystatus.core.io.JSONIO(io, skiplines=2)[source]

Bases: object

parse_line(line)[source]

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

read()[source]

Iterate over all JSON input (Generator)

class i3pystatus.core.io.StandaloneIO(click_events, modules, keep_alive, interval=1)[source]

Bases: i3pystatus.core.io.IOHandler

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

async_refresh()[source]

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

compute_treshold_interval()[source]

Current method is to compute average from all intervals.

n = -1
proto = [{'version': 1, 'click_events': True}, '[', '[]', ',[]']
read()[source]
read_line()[source]
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 = {}
registered(status_handler)[source]
required = set()
run()[source]

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'}
inject(json)[source]
move(position)[source]
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.

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

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
output
position = 0
registered(status_handler)[source]

Called when this module is registered with a status handler

required = set()
run()[source]
send_output()[source]

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.')]
text_to_pango()[source]

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]
get_protected_settings(settings_source)[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

init()[source]

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

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

Bases: object

append(workload)[source]
create_thread(workloads)[source]
create_threads(threads)[source]
partition_workloads(workloads)[source]
resume()[source]
start()[source]
suspend()[source]
wrap(workload)[source]
class i3pystatus.core.threading.Thread(target_interval, workloads=None, start_barrier=1)[source]

Bases: threading.Thread

append(workload)[source]
branch(vtime, bound)[source]
execute_workloads()[source]
pop()[source]
resume()[source]
run()[source]
should_execute(workload)[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.

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

Bases: i3pystatus.core.threading.Wrapper

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

Bases: object

i3pystatus.core.threading.unwrap_workload(workload)[source]

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

Parameters:
  • 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

KeyConstraintDict.missing()[source]

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]
get(find_id)[source]
class i3pystatus.core.util.MultiClickHandler(callback_handler, timeout)[source]

Bases: object

check_double(button)[source]
clear_timer()[source]
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.

Parameters:
  • 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.bytes_info_dict(in_bytes)[source]
i3pystatus.core.util.convert_position(pos, json)[source]
i3pystatus.core.util.flatten(l)[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.

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

Formatted string

i3pystatus.core.util.get_module(function)[source]

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.
@get_module
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

require()

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

Removes a prefix from string

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

string without the prefix

i3pystatus.core.util.make_bar(percentage)[source]

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).

Parameters:
  • 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.
Returns:

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.

Parameters:
  • 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’).
Returns:

Bar as a string

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

Draws a vertical bar made of unicode characters.

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

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

Parameters:
  • predicate – function taking an item returning bool
  • iterable – iterable
Returns:

iterable (generator function)

i3pystatus.core.util.require(predicate)[source]

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

internet

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.

i3pystatus.core.util.user_open(url_or_command)[source]

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