API Reference

Contents

API Reference#

Wakepy API is still experimental 🚧

Since wakepy is still 0.x.x, the API might change without further notice from one release to another. After that, breaking changes should occur only part of a major release (e.g. 1.x.x -> 2.0.0).

wakepy.keep.running([methods, omit, ...])

Create a wakepy mode (a context manager) for keeping programs running.

wakepy.keep.presenting([methods, omit, ...])

Create a wakepy mode (a context manager) for keeping a system running and showing content.

Wakepy Modes#

wakepy.keep.running(methods: StrCollection | None = None, omit: StrCollection | None = None, methods_priority: MethodsPriorityOrder | None = None, on_fail: OnFail = 'warn', dbus_adapter: Type[DBusAdapter] | DBusAdapterTypeSeq | None = None) Mode#

Create a wakepy mode (a context manager) for keeping programs running.

➡️ Documentation of keep.running mode. ⬅️

Parameters:
methods: list, tuple or set of str

The names of Methods to select from the keep.running mode; a “whitelist” filter. Means “use these and only these Methods”. Any Methods in methods but not in the keep.running mode will raise a ValueError. Cannot be used same time with omit. Optional.

omit: list, tuple or set of str or None

The names of Methods to remove from the keep.running mode; a “blacklist” filter. Any Method in omit but not in the keep.running mode will be silently ignored. Cannot be used same time with methods. Optional.

methods_priority: list[str | set[str]]

The priority order for the methods to be used when entering the keep.running mode. You may use this parameter to force or suggest the order in which Methods are used. Any methods not explicitly supported by the current platform will automatically be unused (no need to add them here). The format is a list[str | set[str]], where each string is a Method name. Any method within a set will have equal user-given priority, and they are prioritized with the automatic prioritization rules. The first item in the list has the highest priority. All method names must be unique and must be part of the keep.running Mode.

The asterisk (‘*’) can be used to mean “all other methods” and may occur only once in the priority order, and cannot be part of a set. If asterisk is not part of the methods_priority, it will be added as the last element automatically.

on_fail: “error” | “warn” | “pass” | Callable

Determines what to do in case mode activation fails. Valid options are: “error”, “warn”, “pass” and a callable. If the option is “error”, raises ActivationError. Is selected “warn”, issues a warning. If “pass”, does nothing. If on_fail is a callable, it must take one positional argument: result, which is an instance of ActivationResult. The ActivationResult contains more detailed information about the activation process.

dbus_adapter: class or sequence of classes

Optional argument which can be used to define a custom DBus adapter. If given, should be a subclass of DBusAdapter, or a list of such.

Returns:
keep_running_mode: Mode

The context manager for keeping a system running.

Examples

>>> with keep.running() as k:
>>>     # do something that takes a long time.
wakepy.keep.presenting(methods: StrCollection | None = None, omit: StrCollection | None = None, methods_priority: MethodsPriorityOrder | None = None, on_fail: OnFail = 'warn', dbus_adapter: Type[DBusAdapter] | DBusAdapterTypeSeq | None = None) Mode#

Create a wakepy mode (a context manager) for keeping a system running and showing content.

➡️ Documentation of keep.presenting mode. ⬅️

Parameters:
methods: list, tuple or set of str

The names of Methods to select from the keep.presenting mode; a “whitelist” filter. Means “use these and only these Methods”. Any Methods in methods but not in the keep.presenting mode will raise a ValueError. Cannot be used same time with omit. Optional.

omit: list, tuple or set of str or None

The names of Methods to remove from the keep.presenting mode; a “blacklist” filter. Any Method in omit but not in the keep.presenting mode will be silently ignored. Cannot be used same time with methods. Optional.

methods_priority: list[str | set[str]]

The priority order for the methods to be used when entering the keep.presenting mode. You may use this parameter to force or suggest the order in which Methods are used. Any methods not explicitly supported by the current platform will automatically be unused (no need to add them here). The format is a list[str | set[str]], where each string is a Method name. Any method within a set will have equal user-given priority, and they are prioritized with the automatic prioritization rules. The first item in the list has the highest priority. All method names must be unique and must be part of the keep.presenting Mode.

The asterisk (‘*’) can be used to mean “all other methods” and may occur only once in the priority order, and cannot be part of a set. If asterisk is not part of the methods_priority, it will be added as the last element automatically.

on_fail: “error” | “warn” | “pass” | Callable

Determines what to do in case mode activation fails. Valid options are: “error”, “warn”, “pass” and a callable. If the option is “error”, raises ActivationError. Is selected “warn”, issues a warning. If “pass”, does nothing. If on_fail is a callable, it must take one positional argument: result, which is an instance of ActivationResult. The ActivationResult contains more detailed information about the activation process.

dbus_adapter: class or sequence of classes

Optional argument which can be used to define a custom DBus adapter. If given, should be a subclass of DBusAdapter, or a list of such.

Returns:
keep_presenting_mode: Mode

The context manager for keeping a system presenting content.

Examples

>>> with keep.presenting() as k:
>>>     # do something that takes a long time.

Wakepy Core#

class wakepy.Mode(method_classes: list[Type[Method]], methods_priority: MethodsPriorityOrder | None = None, name: ModeName | str | None = None, on_fail: OnFail = 'warn', dbus_adapter: Type[DBusAdapter] | DBusAdapterTypeSeq | None = None)#

A mode is something that is activated (entered in) and deactivated (exited from). Each Mode instance is created with a set of Method classes, and each one of the Methods may be used to activate the Mode. There are multiple Methods for each Mode as there are multiple different operating systems, platforms and desktop environments which might need different activation strategy, but for a single system only one Method would be enough for Mode activation. The rest are typically just for supporting other platforms/DEs/etc.

Modes are implemented as context managers, and user code runs when the mode is active. When the mode is active, there is a possibility to run a heartbeat (implemented in a future version).

Purpose of Mode:

  • Provide the main API of wakepy for the user

  • Provide __enter__ and __exit__ for fulfilling the context manager protocol

  • Provide easy way to define list of Methods to be used for entering a mode

Modes are usually created with a factory function like keep.presenting or keep.running, but using the Mode separately can be used for more fine-grained control.

Parameters:
methods:

The list of Methods to be used for activating this Mode.

methods_priority: list[str | set[str]]

The priority order, which is a list of method names or asterisk (‘*’). The asterisk means “all rest methods” and may occur only once in the priority order, and cannot be part of a set. All method names must be unique and must be part of the methods.

name:

Name of the Mode. Used for communication to user, logging and in error messages (can be “any string” which makes sense to you). Optional.

on_fail: “error” | “warn” | “pass” | Callable

Determines what to do in case mode activation fails. Valid options are: “error”, “warn”, “pass” and a callable. If the option is “error”, raises ActivationError. Is selected “warn”, issues a warning. If “pass”, does nothing. If on_fail is a callable, it must take one positional argument: result, which is an instance of ActivationResult. The ActivationResult contains more detailed information about the activation process.

dbus_adapter:

For using a custom dbus-adapter. Optional. If not given, the default dbus adapter is used, which is JeepneyDBusAdapter

__enter__() Mode#

Called automatically when entering a with block and a instance of Mode is used as the context expression. This tries to activate the Mode using method_classes.

__exit__(exc_type: Type[BaseException] | None, exception: BaseException | None, traceback: TracebackType | None) bool#

Called when exiting the with block.

If with block completed normally, called with (None, None, None) If with block had an exception, called with (exc_type, exc_value, traceback), which is the same as *sys.exc_info.

Will swallow any ModeExit exception. Other exceptions will be re-raised.

activation_result: ActivationResult#

The activation result which tells more about the activation process outcome. See ActivationResult.

active: bool#

True if the mode is active. Otherwise, False. See also: active_method.

property active_method: str | None#

The name of the active Method. None if Mode is not active. See also used_method.

classmethod from_name(mode_name: ModeName, methods: StrCollection | None = None, omit: StrCollection | None = None, methods_priority: MethodsPriorityOrder | None = None, on_fail: OnFail = 'warn', dbus_adapter: Type[DBusAdapter] | DBusAdapterTypeSeq | None = None) Mode#

Creates and returns a Mode based on a mode name.

Parameters:
mode_name: str

The name of the mode to create. Must be an existing Mode name; something that has used as Method.name attribute in a Method subclass. Examples: “keep.running”, “keep.presenting”.

methods: list, tuple or set of str

The names of Methods to select from the mode defined with mode_name; a “whitelist” filter. Means “use these and only these Methods”. Any Methods in methods but not in the selected mode will raise a ValueError. Cannot be used same time with omit. Optional.

omit: list, tuple or set of str or None

The names of Methods to remove from the mode defined with mode_name; a “blacklist” filter. Any Method in omit but not in the selected mode will be silently ignored. Cannot be used same time with methods. Optional.

on_fail: “error” | “warn” | “pass” | Callable

Determines what to do in case mode activation fails. Valid options are: “error”, “warn”, “pass” and a callable. If the option is “error”, raises ActivationError. Is selected “warn”, issues a warning. If “pass”, does nothing. If on_fail is a callable, it must take one positional argument: result, which is an instance of ActivationResult. The ActivationResult contains more detailed information about the activation process.

methods_priority: list[str | set[str]]

The priority order, which is a list of method names or asterisk (‘*’). The asterisk means “all rest methods” and may occur only once in the priority order, and cannot be part of a set. All method names must be unique and must be part of the methods.

dbus_adapter:

For using a custom dbus-adapter. Optional. If not given, the default dbus adapter is used, which is JeepneyDBusAdapter.

Returns:
mode: Mode

The context manager for the selected mode.

method_classes: list[Type[Method]]#

The list of methods associated for this mode as given when creating the Mode. For details, see the documentation of methods in the Mode constructor parameters.

methods_priority: MethodsPriorityOrder | None#

The methods_priority given when creating the Mode.

name: str | None#

The name given when creating the Mode.

on_fail: OnFail#

The on_fail given when creating the Mode.

property used_method: str | None#

The name of the currently used (active) or previously used (already deactivated) Method. None If Mode has never been activated. See also: active_method.

class wakepy.Method(**kwargs: object)#

Methods are objects that are used to switch modes. The phases for changing and being in a Mode is:

  1. enter into a mode by calling enter_mode()

  2. keep into a mode by calling heartbeat() periodically

  3. exit from a mode by calling exit_mode()

Typically one would either implement either enter_mode() and exit_mode() or just heartbeat(), but also the hybrid option is possible.

caniuse() bool | None | str#

Tells if the Method is suitable or unsuitable.

Returns:
result: bool | None | str

True means suitable, None means uncertain, False means unsuitable and a string means unsuitable and tells the reason for it.

Raises:
Exception

If the Method may not be used, may raise an Exception.

enter_mode() None#

Enter to a Mode using this Method. Pair with exit_mode().

Returns:
None:

If entering the mode was successful.

Raises:
Exception

If entering the mode was not succesful.

exit_mode() None#

Exit from a Mode using this Method. Paired with enter_mode().

Returns:
None:

If exiting the mode was successful, or if there was no need to exit from the mode.

Raises:
Exception

If exiting the mode was not succesful.

heartbeat() None#

Called periodically, every heartbeat_period seconds.

NOTE Heartbeat support is not yet implemented.

Ticket: fohrloop/wakepy#109

Returns:
None:

If calling the heartbeat was successful, returns None.

Raises:
Exception

If calling heartbeat was not successful.

heartbeat_period: int | float = 55#

This is the amount of time (in seconds) between two consecutive calls of heartbeat().

classmethod is_unnamed() bool#

Tells if the Method has a name or not. See also name.

Returns:
result: bool

True if the method is without a name. Otherwise False.

mode_name: ModeName | str#

The name of the mode which the Method implements. Each Method subclass implements a single mode, but multiple Methods may implement the same mode. Setting Method.mode_name to foo on one or more Method subclasses defines the Mode foo (Mode classes are themselves not defined or registered anywhere)

name: str = '__unnamed__'#

Human-readable name for the method. Used to define the Methods used for entering a Mode, for example. If given, must be unique across all Methods available in the python process for the mode. Left unset if the Method should not be listed anywhere (e.g. when Method is meant to be subclassed).

supported_platforms: Tuple[PlatformType, ...] = (PlatformType.ANY,)#

Lists the platforms the Method supports. If the current platform is not part of any of the platform types listed in method.supported_platforms, the method is not* going to be used (when used as part of a Mode), and the Method activation result will show a fail in the “PLATFORM” stage.

When subclassing the Method, defining supported_platforms reduces some work required when writing the logic for caniuse(). Additionally, it aids in distinguishing the “PLATFORM” stage fail as a separate type of failure.

As an example, if the Method would support all Unix-like FOSS desktop operating systems, the supported_platforms would be (PlatformType.UNIX_LIKE_FOSS, ). See the PlatformType for all options.

*unless the current platform is unidentified (UNKNOWN). In this case, platform check does not fail (nor succeed), and the activation process continues normally.

Default: Support all platforms.

class wakepy.ActivationResult(results: InitVar[List[MethodActivationResult] | None] = None, mode_name: str | None = None)#

Responsible of keeping track on the possibly successful (max 1), failed and unused methods and providing different view on the results of the activation process. The ActivationResult instances are created in activation process of a Mode like keep.presenting() and keep.running(), and one would not typically initialize one manually.

If you want to:

Parameters:
results:

The MethodActivationResults to be used to fill the ActivationResult

mode_name:

Name of the Mode. Optional.

active_method: str | None#

The name of the active (successful) Method. If no methods are active, this is None.

failure: bool#

Always opposite of success. Included for convenience. See also: get_failure_text().

get_failure_text() str#

Gets information about a failure as text. In case the mode activation was successful, returns an empty string.

This is only intended for interactive use. Users should not rely on the exact text format returned by this function as it may change without a notice. For programmatic use cases, it is advisable to use query(), instead.

See also

list_methods, query
list_methods(ignore_platform_fails: bool = True, ignore_unused: bool = False) list[MethodActivationResult]#

Get a list of the methods present in the activation process, and their activation results. This is the higher-level interface. If you want more control, use query(). The returned methods are in the order as given in when initializing ActivationResult. If you did not create the ActivationReult manually, the methods are in the priority order; the highest priority methods (those which are/were tried first) are listed first.

Parameters:
ignore_platform_fails: bool

If True, ignores plaform support check fail. This is the default as usually one is not interested in methods which are meant for other platforms. If False, includes also platform fails. Default: True.

ignore_unused: bool

If True, ignores all unused / remaining methods. Default: False.

See also

query
mode_name: str | None = None#

Name of the Mode. If the associated Mode does not have a name, the mode_name will be None.

query(success: Sequence[bool | None] = (True, False, None), fail_stages: Sequence[StageName | Literal['NONE', 'PLATFORM_SUPPORT', 'REQUIREMENTS', 'ACTIVATION']] = (StageName.PLATFORM_SUPPORT, StageName.REQUIREMENTS, StageName.ACTIVATION)) list[MethodActivationResult]#

Get a list of the methods present in the activation process, and their activation results. This is the lower-level interface. If you want easier access, use list_methods(). The methods are in the order as given in when initializing ActivationResult. If you did not create the ActivationResult manually, the methods are in the priority order; the highest priority methods (those which are/were tried first) are listed first.

Parameters:
success:

Controls what methods to include in the output. Options are: True (success), False (failure) and None (method not used). If success = (True, False), returns only methods which did succeed or failer (do not return unused methods).

fail_stages:

The fail stages to include in the output. The options are “PLATFORM_SUPPORT”, “REQUIREMENTS” and “ACTIVATION”.

real_success: bool#

Tells is entering into a mode was successful. This may not faked with the WAKEPY_FAKE_SUCCESS environment variable. See also: success.

success: bool#

Tells is entering into a mode was successful. Note that this may be faked with WAKEPY_FAKE_SUCCESS environment variable e.g. for testing purposes.

class wakepy.MethodActivationResult(method_name: str, mode_name: ModeName | str, success: bool | None, failure_stage: StageName | None = None, failure_reason: str = '')#

This class is a result from using a single Method to activate a mode.

failure_reason: str = ''#

Empty string if activating the Method did not fail. Otherwise, failure reason as string, if provided.

failure_stage: StageName | None = None#

None if the method did not fail. Otherwise, the name of the stage where the method failed.

method_name: str#

The name of the Method this result is for.

mode_name: ModeName | str#

The name of the mode of the Method this result is for.

success: bool | None#

Tells about the result of the activation:

  • True: Using Method was successful

  • False: Using Method failed

  • None: Method is unused

class wakepy.ActivationError#

Raised if the activation of a Mode is not successful and the on-fail action is to raise an Exception. See the on_fail parameter of the Mode constructor. This is a subclass of RuntimeError.

class wakepy.ActivationWarning#

Issued if the activation of a Mode is not successful and the on-fail action is to issue a Warning. See the on_fail parameter of the Mode constructor. This is a subclass of UserWarning.

class wakepy.ModeExit#

This can be used to exit from any wakepy mode with block. Just raise it within any with block which is a wakepy mode, and no code below it will be executed.

Examples

You may use ModeExit to exit a with block, like this:

with keep.running():

    # do something

    if SOME_CONDITION:
        print('failure')
        raise ModeExit
    print('success')

This will print just “failure” if SOME_CONDITION is truthy, and just “success” in case it did succeed (never both).

class wakepy.core.constants.PlatformType(value)#

Enumeration for supported platform types. Each identified platform can be categorized to at least one, but potentially many of these. In other words, each IdentifiedPlatformType (type of CURRENT_PLATFORM) maps into one or many PlatformType.

To be used in subclasses of Method in the supported_platforms().

WINDOWS = 'WINDOWS'#

Any Windows version from Windows 10 onwards.

LINUX = 'LINUX'#

Includes any Linux distro. Excludes things like Android & ChromeOS

MACOS = 'MACOS'#

Mac OS (Darwin)

FREEBSD = 'FREEBSD'#

FreeBSD. Also includes GhostBSD

UNKNOWN = 'UNKNOWN'#

Any non-identified platform

BSD = 'BSD'#

Any BSD system (Currently just FreeBSD / GhostBSD, but is likely to change in the future).

UNIX_LIKE_FOSS = 'UNIX_LIKE_FOSS'#

Unix-like desktop environment, but FOSS. Includes: LINUX and BSD. Excludes: Android (mobile), MacOS (non-FOSS), ChromeOS (non-FOSS).

ANY = 'ANY'#

Means any platform.

class wakepy.core.constants.IdentifiedPlatformType(value)#

The type identifier for the (CURRENT_PLATFORM). Any process will be categorized into exactly one IdentifiedPlatformType type; these are mutually exclusive options. Any platform that is not detected will be labeled as UNKNOWN.

See also: PlatformType, which you should use with Method subclasses.

WINDOWS = 'WINDOWS'#
LINUX = 'LINUX'#
MACOS = 'MACOS'#
FREEBSD = 'FREEBSD'#
UNKNOWN = 'UNKNOWN'#
wakepy.core.platform.CURRENT_PLATFORM: IdentifiedPlatformType#

The current platform as detected. If the platform cannot be detected, defaults to UNKNOWN.

DBus Adapter#

DBus adapters are an advanced concept of wakepy. They would be used in such a case where wants to use other D-Bus python library than the default (which is jeepney).

class wakepy.DBusAdapter#

Defines the DBusAdapter interface. This is to be subclassed, and each subclass is usually an implementation for a DBusAdapter using single python (dbus-)library.

When subclassing, implement the process() method. For an example implementation, see JeepneyDBusAdapter.

The __init__() should not take any arguments, and it may raise any subtype of Exception, which simply means that the DBusAdapter may not be used. The Exception will be automatically handled if using the high-level API of wakepy (Modes).

close_connection(connection: object) None#

Close a dbus connection. Implement in a subclass

close_connections() None#

Close all the connections open in this adapter.

process(call: DBusMethodCall) object#

Processes a DBusMethodCall.

Parameters:
call: DBusMethodCall

Represents a D-Bus method call with its arguments. As it tells which bus to use (session / system / custom addr), the connection must be created within the process() call (this may of course be cached).

class wakepy.core.DBusMethodCall(method: DBusMethod, args: Dict[str, Any] | Tuple[Any, ...] | List[Any] | None = None)#

Represents a DBus method call with its arguments. Has basic validation for the number of arguments (compare args agains the DBusMethod.params, if the DBusMethod.params are defined).

Note: Does not check for validity of args against the input parameter signature. This is done only by the underlying DBus library when doing the dbus method calls.

args: Tuple[Any, ...]#

The method args (positional).

get_kwargs() dict[str, Any] | None#

Get a keyword-argument representation (dict) of the args. If the DBusMethod (self.method) does not have params defined, returns None.

method: DBusMethod#

The method which is the target of the call. Must be completely defined.

class wakepy.core.DBusMethod(name: str, signature: str | None, params: tuple[str, ...] | None = None, output_signature: str | None = None, output_params: tuple[str, ...] | None = None, service: str | None = None, path: str | None = None, interface: str | None = None, bus: str | BusType | None = BusType.SESSION)#

The dbus method specification. Uniquely defines a D-Bus method.

It is said to be completely defined, when it is tied to a DBusAddress; when it has bus, service, path and interface. Otherwise, it is partially defined. Tying is done with the .of() method.

bus: str | BusType | None#

The type of message bus used. Should be “SESSION” or “SYSTEM”. Each running dbus-daemon process provides a new message bus. If omitted, session bus is assumed.

completely_defined() bool#

Check if the DBusMethod is completely defined.

interface: str | None#

The name of the interface on the object. Interface defines which methods (or: members) are available on the object. One interface can, and usually does, define multiple methods.

Example: “org.spam.Manager”

name: str#

name of the method, without the interface part. For example if creating method for “org.spam.Manager.SomeMethod”, the method name is “SomeMethod”.

of(addr: DBusAddress) DBusMethod#

Ties a DBusAddress to a DBusMethod, forming a completely defined DBusMethod. Returns a new DBusMethod object.

output_params: tuple[str, ...] | None#

The names of the output parameters defined by the output_signature. This is optional, but highly recommended, as it serves as documentation and removes the need for writing comments for the signature.

output_signature: str | None#

The signature for the method output / return values. See the docs for signature.

params: tuple[str, ...] | None#

The names of the input arguments defined by the signature. This is optional, but highly recommended, as it serves as documentation and removes the need for writing comments for the signature.

path: str | None#

The path of the object to connect with. One object, defined by the bus, service and path, might have multiple interfaces.

Example: “org/spam/Manager”

service: str | None#

The well known bus name of the dbus service to connect with. This is like a domain address, but on D-Bus. There might be multiple objects (specified by their paths) with multiple interfaces on single service.

Example: “org.spam.Manager”

signature: str | None#

The signature for the method input parameters.

The types are: (Conventional name, ASCII type-code, meaning):

BYTE    y (121) Unsigned 8-bit integer
BOOLEAN b (98)  Boolean value: 0 is false, 1 is true
INT16   n (110) Signed 16-bit integer
UINT16  q (113) Unsigned 16-bit integer
INT32   i (105) Signed 32-bit integer
UINT32  u (117) Unsigned 32-bit integer
INT64   x (120) Signed 64-bit integer
UINT64  t (116) Unsigned 64-bit integer
DOUBLE  d (100) IEEE 754 double-precision floating point
UNIX_FD h (104) Unsigned 32-bit integer representing an index into an
                out-of-band array of file descriptors, transferred via
                some platform-specific mechanism
STRING  s (115) String

Ref: dbus-specification

to_call(args: Dict[str, Any] | Tuple[Any, ...] | List[Any] | None = None) DBusMethodCall#

Convert to DBusMethodCall.

Parameters:
args:

The arguments to the D-Bus Method call.

class wakepy.JeepneyDBusAdapter#

An implementation of DBusAdapter using jeepney. Can be used to process DBusMethodCalls (communication with DBus services over a dbus-daemon).

close_connection(connection: DBusConnection) None#

Close a dbus connection. Implement in a subclass

process(call: DBusMethodCall) object#

Processes a DBusMethodCall.

Parameters:
call: DBusMethodCall

Represents a D-Bus method call with its arguments. As it tells which bus to use (session / system / custom addr), the connection must be created within the process() call (this may of course be cached).