API Reference

Contents

API Reference#

Wakepy Modes#

There are two different modes in wakepy: The keep.running and keep.presenting. See the Wakepy Modes for more detailed explanations what they do and the User Guide for examples.

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

Create a wakepy Mode (a context manager / decorator) for keeping programs running.

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

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

wakepy.keep.running(func: Callable[P, R]) Callable[P, R]#
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 / decorator) 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.

See the How to control order of Methods section in the documentation for more information.

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 ActivationWarning. 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:
Mode | func

If not used as a decorator, returns a context manager Mode instance. If used as a decorator, returns a function that automatically enters the keep.running mode when called (this automatically creates a new context manager and uses it).

Examples

Using the decorator syntax:

from wakepy import keep

@keep.running
def long_running_function():
    # do something that takes a long time.

New in version 1.0.0: The decorator syntax for keep.running was added in version 1.0.0.

Using the context manager syntax:

from wakepy import keep

with keep.running() as m:
    # do something that takes a long time.
wakepy.keep.presenting(func: Callable[P, R]) Callable[P, R]#
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 / decorator) 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.

See the How to control order of Methods section in the documentation for more information.

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 ActivationWarning. 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:
Mode | func

If not used as a decorator, returns a context manager Mode instance. If used as a decorator, returns a function that automatically enters the keep.presenting mode when called (this automatically creates a new context manager and uses it).

Examples

Using the decorator syntax:

from wakepy import keep

@keep.presenting
def long_running_function():
    # do something that takes a long time.

New in version 1.0.0: The decorator syntax for keep.presenting was added in version 1.0.0.

Using the context manager syntax:

from wakepy import keep

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

Wakepy Core#

class wakepy.Mode(params: _ModeParams)#

Mode instances are the most important objects, and they provide the main API of wakepy for the user. Typically, Mode instances are created with the factory functions like keep.presenting() and keep.running()

The Mode instances are context managers , which means that they can be used with the with statement, like this:

with keep.running() as m:
    type(m) # <class 'wakepy.Mode'>

The factory functions (and the Mode instances) are also decorators, which means you can also use them like this:

@keep.running
def long_running_function():
    # do something

For more information about how to use the Mode instances, see the User Guide.

active: bool#

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

result: ActivationResult#

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

Changed in version 1.0.0: Renamed from activation_result to result.

name: str | None#

The name of the mode. Examples: “keep.running” for the keep.running mode and “keep.presenting” for the keep.presenting mode.

method: MethodInfo | None#

The MethodInfo representing the currently used (active) or previously used (already deactivated) Method. None if the Mode has not ever been successfully activated. See also active_method.

New in version 1.0.0: The method attribute was added in wakepy 1.0.0 to replace the deprecated used_method attribute.

active_method: MethodInfo | None#

The MethodInfo representing the currently used (active) Method. None if the Mode is not active. See also used_method.

Changed in version 1.0.0: The active_method is now a MethodInfo instance instead of a str representing the method name.

on_fail: OnFail#

Tells what the mode does in case the activation fails. This can be “error”, “warn”, “pass” or a callable. If “error”, raises ActivationError. If “warn”, issues a ActivationWarning. If “pass”, does nothing. If on_fail is a callable, it is called with an instance of ActivationResult. For mode information, refer to the on-fail actions in the user guide.

methods_priority: MethodsPriorityOrder | None#

The priority order for the methods to be used when entering the Mode. For more detailed explanation, see the methods_priority argument of the keep.presenting or keep.running factory functions.

probe_all_methods() ProbingResults#

Probe all methods for a mode.

Unlike normal activation (which stops on first success and keeps method active), this tests all methods and deactivates each after testing.

You can use this to see which methods would work on the current system (and which would not). The CLI command wakepy methods uses this function internally.

New in version 1.0.0.

Returns:
ProbingResults

Result containing activation outcomes for each tested Method. Tells which Methods would work on the current system and which would not.

property activation_result: ActivationResult#

Deprecated since version 1.0.0: Use result instead. This property will be removed in a future version of wakepy.

property used_method: str | None#

Deprecated since version 1.0.0: Use method instead. This property will be removed in a future version of wakepy.

class wakepy.MethodInfo(name: str, mode_name: str, supported_platforms: Tuple[PlatformType, ...])#

MethodInfo is a read-only object which contains information about the used wakepy Method. You’ll most likely bump into this through the Mode.active_method or Mode.method when using one of the Wakepy Modes. For example:

>>> with keep.running() as m:
...      print('Used method:', m.method)
...      print(type(m.method))
...
Used method: org.gnome.SessionManager
<class 'wakepy.core.method.MethodInfo'>

See also

See Wakepy Methods for a full listing of the available Methods.

New in version 1.0.0.

mode_name: str#

The name of the mode the method implements. Examples: “keep.running” for the keep.running mode and “keep.presenting” for the keep.presenting mode.

name: str#

Name of the Method. See full listing of different methods at Wakepy Methods. Examples: “SetThreadExecutionState”, “caffeinate”.

supported_platforms: Tuple[PlatformType, ...]#

The list the platforms the Method supports.

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

Responsible for keeping track of the possibly successful (max 1), failed and unused methods and providing a different view of 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.

method: MethodInfo | None#

The MethodInfo about the used (successful) Method. If the activation was not successful, this is None.

New in version 1.0.0.: The method attribute was added in wakepy 1.0.0 to replace the deprecated active_method attribute.

property active_method: str | None#

Deprecated since version 1.0.0: Use method instead. This property will be removed in a future version of wakepy.

get_detailed_summary_text(max_width: int = 80, *, success: str = 'SUCCESS', fail: str = 'FAIL', unused: str = 'UNUSED', unsupported: str = 'UNSUPPORTED') str#

Get method activation results with detailed status and reasons.

Parameters:
max_widthint, optional

Maximum width for each line in the output. Default: 80.

successstr, optional

String to use for successful methods.

failstr, optional

String to use for failed methods (non-platform failures).

unusedstr, optional

String to use for unused methods.

unsupportedstr, optional

String to use for platform support failures.

Returns:
str

Formatted output with method names, status, and failure reasons

Examples

>>> print(result.get_detailed_summary_text())
  1. org.freedesktop.PowerManagement
     FAIL: DBusCallError("DBus call of method 'Inhibit' on interface
     'org.freedesktop.PowerManagement.Inhibit' with args ('wakepy',
     'wakelock active') failed with message:
     [org.freedesktop.DBus.Error.ServiceUnknown] ('The name
     org.freedesktop.PowerManagement was not provided by any .service
     files',)")

  2. org.gnome.SessionManager
     SUCCESS

  3. caffeinate
     UNSUPPORTED: caffeinate is not supported on LINUX. The supported
     platforms are: MACOS

  4. SetThreadExecutionState
     UNSUPPORTED: SetThreadExecutionState is not supported on LINUX.
     The supported platforms are: WINDOWS

New in version 1.0.0.

See also

Use this when you need to understand why methods failed. For compact output, use get_summary_text(). To show only failures, use get_failure_text().

get_failure_text(style: Literal['block', 'inline'] = 'block') 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 or for logging purposes. 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(), or list_methods() instead.

Parameters:
style: “block” | “inline”

The style of the failure text. “block” adds newlines in the text and makes it easier to read, while “inline” returns a single line string (useful for logging). Default: “block”.

Examples

>>> # Assuming the activation will fail for some reason
>>> with keep.presenting() as m:
>>>     # do stuff
>>>
>>> print(m.result.get_failure_text())
Could not activate wakepy Mode "keep.running"!

Tried Methods (in the order of attempt):

1. org.freedesktop.PowerManagement
    Reason: DBusCallError("DBus call of method 'Inhibit' on interface
    'org.freedesktop.PowerManagement.Inhibit' with args ('wakepy', 'wakelock
    active') failed with message: [org.freedesktop.DBus.Error.ServiceUnknown]
    ('The name org.freedesktop.PowerManagement was not provided by any
    .service files',)")

2. org.gnome.SessionManager
    Reason: RuntimeError('Intentional failure here (for demo purposes)')

3. caffeinate
    Reason: Current platform (LINUX) is not in supported platforms: MACOS

4. SetThreadExecutionState
    Reason: Current platform (LINUX) is not in supported platforms: WINDOWS
>>> # Inline style
>>> print(m.result.get_failure_text('inline'))
Could not activate wakepy Mode "keep.running"! Tried Methods (in the order of attempt): (#1, org.freedesktop.PowerManagement, Reason: DBusCallError("DBus call of method 'Inhibit' on interface 'org.freedesktop.PowerManagement.Inhibit' with args ('wakepy', 'wakelock active') failed with message: [org.freedesktop.DBus.Error.ServiceUnknown] ('The name org.freedesktop.PowerManagement was not provided by any .service files',)")), (#2, caffeinate, Reason: caffeinate is not supported on LINUX. The supported platforms are: MACOS), (#3, SetThreadExecutionState, Reason: SetThreadExecutionState is not supported on LINUX. The supported platforms are: WINDOWS). The format of each item in the list is (index, method_name, failure_reason).

Changed in version 1.0.0.: The style parameter was added in wakepy 1.0.0, and the default style was changed to “block”.

See also

This shows only failures. To include successful methods too, use get_summary_text() or get_detailed_summary_text(). For programmatic access to method results, use list_methods() or query().

get_summary_text(*, index_width: int = 3, name_width: int = 35, status_width: int = 8) str#

Get method activation results as a compact text table.

Parameters:
index_width: int, optional

Width for the index number column. You can also control the level of indent by changing this value.

name_width: int, optional

Maximum width for method name column. Long names will be truncated with “…”.

status_width: int, optional

Width for status column.

Returns:
str

Formatted output with method names and status

Examples

>>> print(result.get_summary_text())
  1. org.freedesktop.PowerManagement             SUCCESS
  2. org.gnome.SessionManager                    FAIL
  3. caffeinate                                  *
  4. SetThreadExecutionState                     *

New in version 1.0.0.

See also

Use this for compact display. For more detailed results, use get_detailed_summary_text(). To show only failures, use get_failure_text().

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

Get a list of methods involved in the activation process together with their activation results.

This is the higher-level interface. For more finer-grained control, use query().

The returned 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.

Changed in version 1.0.0.: The parameters are now keyword-only (See: wakepy/wakepy#527)

Parameters:
ignore_platform_fails: bool

If True, ignores platform 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.

mode_name: str | None = None#

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

Changed in version 1.0.0.: The mode_name is now always a string (or None) instead of ModeName.

query(success: Sequence[bool | None] = (True, False, None), fail_stages: Sequence[StageName | Literal['NONE', 'WAKEPY_FORCE_FAILURE', 'PLATFORM_SUPPORT', 'REQUIREMENTS', 'ACTIVATION']] = (StageName.WAKEPY_FORCE_FAILURE, 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 fail (do not return unused methods).

fail_stages:

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

success: bool#

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

real_success: bool#

Tells if entering into a mode was successful. This may not be faked with the WAKEPY_FAKE_SUCCESS environment variable.

See also: success.

failure: bool#

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

wakepy.current_mode() Mode#

Gets the current Mode instance for the current thread and context.

Returns:
current_mode: Mode | None

The current Mode instance for the thread and context. None, if not entered in any Mode.

Raises:
NoCurrentModeError

If there are no Modes active in the call stack, raises a NoCurrentModeError.

Notes

  • This function cannot return any Modes from other threads. This means that even if you have entered a Mode in an another thread, but not in the current thread, this function will return None

  • You may access the current Mode instance from anywhere throughout the call stack, as long you are in the same thread and context.

  • You only need the current_mode() if you’re using the decorator syntax, or if you’re checking the mode within a function which is lower in the call stack.

  • Internally, a ContextVar. is used to store the current Mode instance for the current thread and context.

Examples

Decorator syntax: You may use this function to get the current Mode instance, when using the decorator syntax , like this:

from wakepy import keep, current_mode

@keep.presenting
def long_running_function():
    m = current_mode()
    print(f"Used method is: {m.method}")

Deeper in the call stack: You can also use this function to get the current Mode instance in a function which is lower in the call stack, like this:

from wakepy import keep, current_mode

def long_running_function():
    with keep.presenting():
        sub_function()

def sub_function():
    m = current_mode()
    print(f"Used method is: {m.method}")

New in version 1.0.0.

wakepy.global_modes() List[Mode]#

Gets all the Mode instances from all threads and active contexts for the current python process.

While the current_mode() returns the innermost Mode for the current thread and context, this function returns all Modes from all threads and contexts.

Returns:
all_modes: List[Mode]

The list of all active wakepy Mode instances from all threads and active contexts.

New in version 1.0.0: ..

See also

current_mode() for getting the current Mode instance and modecount() for getting the number of all Modes from all threads and contexts.

wakepy.modecount() int#

The global mode count across all threads and contexts, for the current python process

Returns:
mode_count: int

The number of all Mode instances from all threads and active contexts.

New in version 1.0.0: ..

See also

current_mode() for getting the current Mode instance and global_modes() for getting all the Modes from all threads and contexts.

class wakepy.MethodActivationResult(method: MethodInfo, 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.

When activating a wakepy Mode, the activation process:

  • Creates a list of Methods to try, and prioritizes them

  • Tries to activate the mode by using the Methods in the list, one by one.

For each Method activation attempt, a MethodActivationResult is created. The ActivationResult then collects all the MethodActivationResult instances and provides a higher-level interface to access the results of the activation process.

method: MethodInfo#

Information about the wakepy Method this result is for.

New in version 1.0.0.

success: bool | None#

Tells about the result of the activation:

  • True: Using Method was successful

  • False: Using Method failed

  • None: Method is unused

failure_stage: StageName | None = None#

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

failure_reason: str = ''#

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

property mode_name: str#

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

property method_name: str#

The name of the Method this result is for.

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

Result from probing all Methods for a Mode. Tells which Methods would work on the current system and which would not.

No Methods can be UNUSED in a ProbingResults as all Methods are probed.

New in version 1.0.0.

methods: List[MethodInfo]#

List of all MethodInfo about wakepy Methods used, in the order they were tried.

get_detailed_summary_text(max_width: int = 80, *, success: str = 'SUCCESS', fail: str = 'FAIL', unused: str = 'UNUSED', unsupported: str = 'UNSUPPORTED') str#

Get method activation results with detailed status and reasons.

Parameters:
max_widthint, optional

Maximum width for each line in the output. Default: 80.

successstr, optional

String to use for successful methods.

failstr, optional

String to use for failed methods (non-platform failures).

unusedstr, optional

String to use for unused methods.

unsupportedstr, optional

String to use for platform support failures.

Returns:
str

Formatted output with method names, status, and failure reasons

Examples

>>> print(result.get_detailed_summary_text())
  1. org.freedesktop.PowerManagement
     FAIL: DBusCallError("DBus call of method 'Inhibit' on interface
     'org.freedesktop.PowerManagement.Inhibit' with args ('wakepy',
     'wakelock active') failed with message:
     [org.freedesktop.DBus.Error.ServiceUnknown] ('The name
     org.freedesktop.PowerManagement was not provided by any .service
     files',)")

  2. org.gnome.SessionManager
     SUCCESS

  3. caffeinate
     UNSUPPORTED: caffeinate is not supported on LINUX. The supported
     platforms are: MACOS

  4. SetThreadExecutionState
     UNSUPPORTED: SetThreadExecutionState is not supported on LINUX.
     The supported platforms are: WINDOWS

New in version 1.0.0.

See also

Use this when you need to understand why methods failed. For compact output, use get_summary_text(). To show only failures, use get_failure_text().

get_failure_text(style: Literal['block', 'inline'] = 'block') 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 or for logging purposes. 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(), or list_methods() instead.

Parameters:
style: “block” | “inline”

The style of the failure text. “block” adds newlines in the text and makes it easier to read, while “inline” returns a single line string (useful for logging). Default: “block”.

Examples

>>> # Assuming the activation will fail for some reason
>>> with keep.presenting() as m:
>>>     # do stuff
>>>
>>> print(m.result.get_failure_text())
Could not activate wakepy Mode "keep.running"!

Tried Methods (in the order of attempt):

1. org.freedesktop.PowerManagement
    Reason: DBusCallError("DBus call of method 'Inhibit' on interface
    'org.freedesktop.PowerManagement.Inhibit' with args ('wakepy', 'wakelock
    active') failed with message: [org.freedesktop.DBus.Error.ServiceUnknown]
    ('The name org.freedesktop.PowerManagement was not provided by any
    .service files',)")

2. org.gnome.SessionManager
    Reason: RuntimeError('Intentional failure here (for demo purposes)')

3. caffeinate
    Reason: Current platform (LINUX) is not in supported platforms: MACOS

4. SetThreadExecutionState
    Reason: Current platform (LINUX) is not in supported platforms: WINDOWS
>>> # Inline style
>>> print(m.result.get_failure_text('inline'))
Could not activate wakepy Mode "keep.running"! Tried Methods (in the order of attempt): (#1, org.freedesktop.PowerManagement, Reason: DBusCallError("DBus call of method 'Inhibit' on interface 'org.freedesktop.PowerManagement.Inhibit' with args ('wakepy', 'wakelock active') failed with message: [org.freedesktop.DBus.Error.ServiceUnknown] ('The name org.freedesktop.PowerManagement was not provided by any .service files',)")), (#2, caffeinate, Reason: caffeinate is not supported on LINUX. The supported platforms are: MACOS), (#3, SetThreadExecutionState, Reason: SetThreadExecutionState is not supported on LINUX. The supported platforms are: WINDOWS). The format of each item in the list is (index, method_name, failure_reason).

Changed in version 1.0.0.: The style parameter was added in wakepy 1.0.0, and the default style was changed to “block”.

See also

This shows only failures. To include successful methods too, use get_summary_text() or get_detailed_summary_text(). For programmatic access to method results, use list_methods() or query().

get_summary_text(*, index_width: int = 3, name_width: int = 35, status_width: int = 8) str#

Get method activation results as a compact text table.

Parameters:
index_width: int, optional

Width for the index number column. You can also control the level of indent by changing this value.

name_width: int, optional

Maximum width for method name column. Long names will be truncated with “…”.

status_width: int, optional

Width for status column.

Returns:
str

Formatted output with method names and status

Examples

>>> print(result.get_summary_text())
  1. org.freedesktop.PowerManagement             SUCCESS
  2. org.gnome.SessionManager                    FAIL
  3. caffeinate                                  *
  4. SetThreadExecutionState                     *

New in version 1.0.0.

See also

Use this for compact display. For more detailed results, use get_detailed_summary_text(). To show only failures, use get_failure_text().

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

Get a list of methods involved in the activation process together with their activation results.

This is the higher-level interface. For more finer-grained control, use query().

The returned 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.

Changed in version 1.0.0.: The parameters are now keyword-only (See: wakepy/wakepy#527)

Parameters:
ignore_platform_fails: bool

If True, ignores platform 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.

mode_name: str | None = None#

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

Changed in version 1.0.0.: The mode_name is now always a string (or None) instead of ModeName.

query(success: Sequence[bool | None] = (True, False, None), fail_stages: Sequence[StageName | Literal['NONE', 'WAKEPY_FORCE_FAILURE', 'PLATFORM_SUPPORT', 'REQUIREMENTS', 'ACTIVATION']] = (StageName.WAKEPY_FORCE_FAILURE, 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 fail (do not return unused methods).

fail_stages:

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

success: bool#

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

real_success: bool#

Tells if entering into a mode was successful. This may not be faked with the WAKEPY_FAKE_SUCCESS environment variable.

See also: success.

failure: bool#

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

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.NoCurrentModeError#

Raised when trying to get the current mode but none is active. This is a subclass of RuntimeError.

New in version 1.0.0.

See also

current_mode()

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(*values)#

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(*values)#

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.

class wakepy.ModeName(*values)#

The names of the modes wakepy supports

See: Wakepy Modes for full definitions of the modes.

KEEP_RUNNING = 'keep.running'#
KEEP_PRESENTING = 'keep.presenting'#
class wakepy.Method(**kwargs: object)#

Methods are objects that are used to implement modes. The Method class is an advanced topic in wakepy and typically users of wakepy do not need to interact with it directly. Instead, users will interact with the read-only MethodInfo instances.

The subclassing of Method is the way to implement a new Methods (and Modes) in wakepy.

The different phases of using a Method for activating / keeping / deactivating a Mode are:

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

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

heartbeat() None#

Called periodically, every heartbeat_period seconds.

NOTE Heartbeat support is not yet implemented.

Ticket: wakepy/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#

A name for the mode which the Method implements. The name can be basically anything, and is typically used when you create Mode instances using the Mode._from_name(). For example: “keep.running”. 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 and registers a mode called “foo”.

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.

DBus Adapter#

DBus adapters are an advanced concept of wakepy. They would be used in such a case where one 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 against 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: ForwardRef('str'), signature: ForwardRef('str | None'), params: ForwardRef('Optional[tuple[str, ...]]') = None, output_signature: ForwardRef('str | None') = None, output_params: ForwardRef('Optional[tuple[str, ...]]') = None, service: ForwardRef('Optional[str]') = None, path: ForwardRef('Optional[str]') = None, interface: ForwardRef('Optional[str]') = None, bus: ForwardRef('Optional[Union[str, BusType]]') = 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).