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)[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.
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=0)[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
class i3pystatus.core.desktop.DesktopNotification(title, body, icon='dialog-information', urgency=1, timeout=0)[source]

Bases: i3pystatus.core.desktop.BaseDesktopNotification

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='ANSI_X3.4-1968'>, out=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='ANSI_X3.4-1968'>)[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, 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 = [{'click_events': True, 'version': 1}, '[', '[]', ',[]']
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.

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_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_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`)'), ('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_click(button)[source]

Maps a click event with its associated callback.

Currently implemented events are:

Event Callback setting Button ID
Left click on_leftclick 1
Right click on_rightclick 3
Scroll up on_upscroll 4
Scroll down on_downscroll 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 (int) – The ID of button event received from i3bar.
Returns:Returns True if a valid callback action was executed. False otherwise.
Return type:bool
on_doubledownscroll = None
on_doubleleftclick = None
on_doublerightclick = None
on_doubleupscroll = None
on_downscroll = None
on_leftclick = None
on_rightclick = None
on_upscroll = None
output = None
position = 0
registered(status_handler)[source]

Called when this module is registered with a status handler

required = set()
run()[source]
settings = [('on_leftclick', 'Callback called on left 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_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`)'), ('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_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]
start()[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]
run()[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

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)[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 an, re.IGNORECASE|re.VERBOSE)
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.

Used server is determined by the address class variable which consists of server host name and port number.

Return type:bool

See also

require()

address = ('google-public-dns-a.google.com', 53)
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_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)[source]

Draws a vertical bar made of unicode characters.

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