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).
|
Create a wakepy mode (a context manager) for keeping programs running. |
|
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 = 'error', 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. Ifon_failis a callable, it must take one positional argument: result, which is an instance ofActivationResult. 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 = 'error', 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. Ifon_failis a callable, it must take one positional argument: result, which is an instance ofActivationResult. 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 = 'error', 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.presentingorkeep.running, but using theModeseparately 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. Ifon_failis a callable, it must take one positional argument: result, which is an instance ofActivationResult. 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 = 'error', 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
Methodsubclass. 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. Ifon_failis a callable, it must take one positional argument: result, which is an instance ofActivationResult. 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 ofmethodsin theModeconstructor parameters.
- 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:
enter into a mode by calling
enter_mode()keep into a mode by calling
heartbeat()periodicallyexit from a mode by calling
exit_mode()
Typically one would either implement either
enter_mode()andexit_mode()or justheartbeat(), but also the hybrid option is possible.- caniuse() bool | None | str#
Tells if the Method is suitable or unsuitable.
- Returns:
- result: bool | None | str
Truemeans suitable,Nonemeans uncertain,Falsemeans 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_periodseconds.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
Trueif the method is without a name. OtherwiseFalse.
- 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_nameto foo on one or moreMethodsubclasses defines the Mode foo (Modeclasses 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 themode. Left unset if the Method should not be listed anywhere (e.g. when Method is meant to be subclassed).
- supported_platforms: Tuple[PlatformName, ...] = (PlatformName.LINUX, PlatformName.WINDOWS, PlatformName.MACOS, PlatformName.OTHER)#
Lists the platforms the Method supports. If a platform is not listed in
method.supported_platforms, themethodis not going to be used on the platform (when used as part of aMode), and the Method activation result will show a fail in the âPLATFORMâ stage.When subclassing, defining
supported_platformsreduces some work required when writing the logic forcaniuse(). Additionally, it aids in distinguishing the âPLATFORMâ stage fail as a separate type of failure.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
ActivationResultinstances are created in activation process of aModelikekeep.presenting()andkeep.running(), and one would not typically initialize one manually.If you want to:
Check if the activation was successful: See
successCheck the active method: See
active_methodGet information about activation failure in text format: See
get_failure_text()Know more about the Methods involved: See
list_methods()andquery().
- 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 isNone.
- 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(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
- mode_name: str | None = None#
Name of the
Mode. If the associatedModedoes not have a name, themode_namewill beNone.
- 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â.
See also
- 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.
See also
- 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.
- success: bool | None#
Tells about the result of the activation:
True: Using Method was successfulFalse: Using Method failedNone: Method is unused
- class wakepy.ActivationError#
Raised if the activation of a
Modeis not successful and the on-fail action is to raise an Exception. See theon_failparameter of theModeconstructor. This is a subclass of RuntimeError.
- class wakepy.ActivationWarning#
Issued if the activation of a
Modeis not successful and the on-fail action is to issue a Warning. See theon_failparameter of theModeconstructor. 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
ModeExitto 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_CONDITIONis truthy, and just âsuccessâ in case it did succeed (never both).
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, seeJeepneyDBusAdapter.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
DBusAdapterusing 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).