zensols.cli package

Subpackages

Submodules

zensols.cli.action module

A more object oriented data driven command line set of classes.

class zensols.cli.action.ActionCli(section, class_meta, options=None, mnemonic_includes=None, mnemonic_excludes=<factory>, mnemonic_overrides=None, option_includes=None, option_excludes=<factory>, option_overrides=None, first_pass=False, always_invoke=False, is_usage_visible=True, sort_methods=False)[source]

Bases: PersistableContainer, Dictable

A set of commands that is invokeable on the command line, one for each registered method of a class (usually a dataclasses.dataclass. This contains meta data necesary to create a full usage command line documentation and parse the user’s input.

__init__(section, class_meta, options=None, mnemonic_includes=None, mnemonic_excludes=<factory>, mnemonic_overrides=None, option_includes=None, option_excludes=<factory>, option_overrides=None, first_pass=False, always_invoke=False, is_usage_visible=True, sort_methods=False)
always_invoke: bool = False

If True, always invoke all methods for the action regardless if an action mnemonic and options pertaining to the action are not given by the user/command line. This is useful for configuration first pass type classes like PackageInfoImporter to force the CLI API to invoke it, as otherwise there’s no indication to the CLI that it needs to be called.

class_meta: Class

The target class meta data parsed by ClassInspector

first_pass: bool = False

Whether or not this is a first pass action (i.e. such as setting the level in LogConfigurator).

is_usage_visible: bool = True

Whether the action CLI is included in the usage help.

property meta_datas: Tuple[ActionMetaData, ...]

Return action meta data across all methods.

property methods: Dict[str, ActionCliMethod]

Return the methods for this action CLI with method name keys.

mnemonic_excludes: Set[str]

A list of mnemonicss to exclude, or none if None.

mnemonic_includes: Set[str] = None

A list of mnemonicss to include, or all if None.

mnemonic_overrides: Dict[str, str] = None

The name of the action given on the command line, which defaults to the name of the action.

option_excludes: Set[str]

A list of options to exclude, or none if None.

option_includes: Set[str] = None

A list of options to include, or all if None.

option_overrides: Dict[str, Dict[str, str]] = None

Overrides when creating new OptionMetaData where the keys are the option names (field or method parameter) and the values are the dict that clobbers respective keys.

See:

ActionCliManager._create_op_meta_data()

options: Dict[str, OptionMetaData] = None

Options added by ActionCliManager, which are those options parsed by the entire class metadata.

section: str

The application section to introspect.

sort_methods: bool = False

Whether to sort methods, which has an effect on action usage.

class zensols.cli.action.ActionCliManager(config_factory, apps, cleanups=None, app_removes=None, cleanup_removes=None, decorator_section_format='{section}_decorator', doc=None, default_action=None, force_default=False, usage_config=<factory>)[source]

Bases: PersistableContainer, Dictable

Manages instances of ActionCli. An ActionCli is created from the configuration given by the section. Optionally, another section using decorator_section_format will be read to add additional metadata and configuration to instantiated object. The decorated information is used to help bridge between the class given to be instantiated and the CLI.

See:

actions

See:

actions_by_meta_data_name

CLASS_META_ATTRIBUTE = 'CLI_META'

The class level attribute on application classes containing a stand in (otherwise missing section configuration ActionCli.

SECTION = 'cli'

The application context section.

__init__(config_factory, apps, cleanups=None, app_removes=None, cleanup_removes=None, decorator_section_format='{section}_decorator', doc=None, default_action=None, force_default=False, usage_config=<factory>)
property actions: Dict[str, ActionCli]

Get a list of action CLIs that is used in CommandLineParser to create instances of the application. Each action CLI has a collection of ActionMetaData instances.

Returns:

keys are the configuration sections with the action CLIs as values

property actions_by_meta_data_name: Dict[str, ActionCli]

Return a dict of ActionMetaData instances, each of which is each mnemonic by name and the meta data by values.

property actions_ordered: Tuple[ActionCli, ...]

Return all actions in the order they were given in the configuration.

app_removes: InitVar[Set[str]] = None

`apps, which is helpful when a single section to remove is needed when importing from other files.

Type:

Removes apps from

Type:

obj

apps: Tuple[str, ...]

The application section names.

cleanup_removes: InitVar[Set[str]] = None

Clean ups to remove from cleanups, which is helpful when a single section to remove is needed when importing from other files.

cleanups: Tuple[str, ...] = None

The sections to remove after the application is built.

classmethod combine_meta(parent, cli_meta)[source]

Merge static class CLI metadata of the variable named CLASS_META_ATTRIBUTE.

Parameters:
  • self – this class

  • parent (Type) – the parent class of the caller, which is used to get the parent classes CLI metadata to merge

  • cli_meta (Dict[str, Any]) – the metadata identified by the CLASS_META_ATTRIBUTE

property config: Configurable
config_factory: ConfigFactory

The configuration factory used to create ActionCli instances.

decorator_section_format: str = '{section}_decorator'

Format of ActionCli configuration classes.

default_action: str = None

The default mnemonic use when the user does not supply one.

See:

CommandLineParser.default_action

doc: str = None

The application documentation.

force_default: str = False

When True`, the command parsing will insert the default action when the first non-option isn’t found as an action. However, this leads to ambiguouity in identifiction of the action and is inefficient.

See:

CommandLineParser.force_default

usage_config: UsageConfig

Configuraiton information for the command line help.

exception zensols.cli.action.ActionCliManagerError[source]

Bases: ActionCliError

Raised by ActionCliManager for any problems creating ActionCli instances.

__module__ = 'zensols.cli.action'
class zensols.cli.action.ActionCliMethod(action_meta_data, method)[source]

Bases: Dictable

A “married” action meta data / class method pair. This is a pair of action meta data that describes how to interpret it as a CLI action and the Python class meta data method, which is used later to invoke the action (really command).

__init__(action_meta_data, method)
action_meta_data: ActionMetaData

The action meta data for method.

method: ClassMethod

The method containing information about the source class method to invoke later.

zensols.cli.app module

A more object oriented data driven command line set of classes.

class zensols.cli.app.Action(command_action, cli, meta_data, method_meta)[source]

Bases: Deallocatable, Dictable

An invokable action from the command line the Application class. This class combines the user input from the command line with the meta data from the Python classes given in the configuration.

Combined, these two data sources provide a means to execute an action, which is conceptually one functionality of the application and literally a Python class method.

The class also is somewhat of a facade allowing a client to access data from both sources without needing to know where it comes from via the class’s properties.

__init__(command_action, cli, meta_data, method_meta)
property class_meta: Class

The meta data of the action, which comes from ActionCli.

property class_name: str

Return the class name of the target application instance.

cli: ActionCli

Command line interface of the action meta data.

command_action: CommandAction

The result of the command line parsing of the action. It contains the data parsed on a per action level.

deallocate()[source]

Deallocate all resources for this instance.

meta_data: ActionMetaData

An action represents a link between a command line mnemonic action and a method on a class to invoke.

method_meta: ClassMethod

The metadata of the method to use for the invocation of the action.

property method_name: str

The method to invoke on the target application instance class.

property name: str

The name of the action, which is the form:

<action's section name>.<meta data's name>

property section: str

The section from which the ActionCli was created.

class zensols.cli.app.ActionResult(action, instance, result)[source]

Bases: Dictable

The results of a single method call to an Action instance. There is one of these per action (both first and second pass) provided in ApplicationResult.

__init__(action, instance, result)
action: Action

The action that was used to generate the result.

instance: Any

The application instance.

property name: str
result: Any

The results returned from the invocation on the application instance.

class zensols.cli.app.Application(config_factory, factory, actions)[source]

Bases: Dictable

An invokable application created using command line and application context data. This class creates an instance of the target application instance, then invokes the corresponding action method.

The application has all the first pass actions configured to run and/or given options indicating by the user to run (see first_pass_actions). It also has the second pass action given as a mnemonic, or the single second pass action if there is only one (see second_pas_action).

__init__(config_factory, factory, actions)
actions: Tuple[Action, ...]

The list of actions to invoke in order.

property actions_by_name: Dict[str, Action]

A dictionary of actions by their name.

config_factory: ConfigFactory

The factory used to create the application and its components.

factory: ApplicationFactory

The factory that created this application.

property first_pass_actions: Iterable[Action]

All first pass actions registered in the application and/or indicated by the user to run via the command line.

get_invokable(action_name)[source]

Create an invokable.

Parameters:

action_name (str) – the name of the action, which is also the section name in the configuration

Return type:

Invokable

invoke()[source]

Invoke the application and return the results.

Return type:

ApplicationResult

invoke_but_second_pass()[source]

Invoke first pass actions but not the second pass action.

Return type:

Tuple[Tuple[ActionResult, ...], Invokable]

Returns:

the results from the first pass actions and an invokable for the second pass action

property second_pass_action: Action

The second pass action registered in the application and indicated to execute by the command line input.

class zensols.cli.app.ApplicationFactory(package_resource, app_config_resource='resources/app.conf', children_configs=None, reload_factory=False, reload_pattern=None, error_handler=None)[source]

Bases: PersistableContainer

Boots the application context from the command line. This first loads resource resources/app.conf from this package, then adds app_config_resource from the application package of the client.

__init__(package_resource, app_config_resource='resources/app.conf', children_configs=None, reload_factory=False, reload_pattern=None, error_handler=None)
app_config_resource: Union[str, TextIOBase] = 'resources/app.conf'

The relative resource path to the application’s context if str. If the type is an instance of io.TextIOBase, then read it as a file object.

children_configs: Tuple[Configurable, ...] = None

Any children configurations added to the root level configuration.

property cli_manager: ActionCliManager

The manager that creates the action based CLIs.

property config_factory: ConfigFactory

The configuration factory used to create the application.

create(args=None)[source]

Create the action CLI application.

Parameters:

args (List[str]) – the arguments to the application; if this is a string, it will be converted to a list by splitting on whitespace; this defaults to the output of _get_default_args()

Raises:

ActionCliError – for any missing data or misconfigurations

Return type:

Application

classmethod create_harness(**kwargs)[source]

Create and return a CliHarness.

Parameters:

kwargs – the keyword arguments given to the harness initializer

error_handler: Callable = None

A callable that takes an Exception and this instance as a paramters to handle the error. This can be set to ApplicationFailure for programatic entry to this class (see CliHarness).

get_instance(args=None)[source]

Create the invokable instance of the application.

Parameters:

args (Union[List[str], str]) – the arguments to the application; if this is a string, it will be converted to a list by splitting on whitespace; this defaults to the output of _get_default_args()

Raises:

ActionCliError – for any missing data or misconfigurations

Return type:

Any

Returns:

the invokable instance of the application

invoke(args=None)[source]

Creates and invokes the entire application returning the result of the second pass action.

;param args: the arguments to the application; if this is a string, it

will be converted to a list by splitting on whitespace; this defaults to the output of _get_default_args()

Raises:

ActionCliError – for any missing data or misconfigurations

Return type:

ActionResult

Returns:

the result of the second pass action

invoke_protect(args=None)[source]

Same as invoke(), but protect against Exception and SystemExit. If an error is raised while invoking, it is logged and returned.

;param args: the arguments to the application; if this is a string, it

will be converted to a list by splitting on whitespace; this defaults to the output of _get_default_args()

Return type:

Union[ActionResult, ApplicationFailure]

Returns:

the result of the second pass action or an ApplicationFailure if Exception or SystemExit is raised

package_resource: Union[str, PackageResource]

The application package resource (i.e. zensols.someappname). This field is converted to a package if given as a string during post initialization.

property parser: CommandLineParser

Used to parse the command line.

reload_factory: bool = False

If True, reload classes in ImportConfigFactory.

See:

_create_config_factory()

reload_pattern: Union[re.Pattern, str] = None

If set, reload classes that have a fully qualified name that match the regular expression regarless of the setting reload in ImportConfigFactory.

See:

_create_config_factory()

_handle_error(ex)[source]

Handle errors raised during the execution of the application.

See:

invoke()

class zensols.cli.app.ApplicationObserver[source]

Bases: ABC

Extended by application targets to get call backs and information from the controlling Application. Method _application_created() is invoked for each call back.

abstract _application_created(app, action)[source]

Called just after the application target is created.

Parameters:

app (Application) – the application that created the application target

class zensols.cli.app.ApplicationResult(action_results)[source]

Bases: Dictable

A container class of the results of an application invocation with Application.invoke(). This is keyed by index of the actions given in actions.

__init__(action_results)
action_results: Tuple[ActionResult, ...]

Both first and second pass action results. These are provided in the same order for which was executed when the class:.Application ran, which is that same order provided to the ActionCliManager.

property by_name: Dict[str, ActionResult]

.Action.name).

Type:

Per action results keyed by action name (obj

property second_pass_result: ActionResult

The single second pass result of that action indicated to invoke on the command line by the user.

class zensols.cli.app.Invokable(action, instance, method, args, kwargs)[source]

Bases: object

A callable that invokes an Action. This is used by Application to invoke the entire CLI application.

__init__(action, instance, method, args, kwargs)
action: Action

The action used to create this instance.

args: Tuple[Any, ...]

The arguments used when calling method.

instance: Any

The instantiated object generated from action.

kwargs: Dict[str, Any]

The keyword arguments used when calling method.

method: Callable

The object method bound to instance to be called.

zensols.cli.command module

Classes to parse command line arguments.

class zensols.cli.command.CommandAction(meta_data, options, positional)[source]

Bases: Dictable

The output of the CommandLineParser for each parsed action.

__init__(meta_data, options, positional)
meta_data: ActionMetaData

The action parsed from the command line.

property name: str

The name of the action.

options: Dict[str, Any]

The options given as switches.

positional: Tuple[str, ...]

The positional arguments parsed.

class zensols.cli.command.CommandActionSet(actions)[source]

Bases: Deallocatable, Dictable

The actions that are parsed by CommandLineParser as the output of the parse phase. This is indexable by command action name and iterable across all actions. Properties first_pass_actions and second_pass_action give access to the split from the respective types of actions.

__init__(actions)
actions: Tuple[CommandAction, ...]

The actions parsed. The first N actions are first pass where as the last is the second pass action.

property by_name: Dict[str, CommandAction]

Command actions by name keys.

deallocate()[source]

Deallocate all resources for this instance.

property first_pass_actions: Iterable[CommandAction]

All first pass actions.

property second_pass_action: CommandAction

The single second pass action.

class zensols.cli.command.CommandLineConfig(actions)[source]

Bases: PersistableContainer, Dictable

Given to configure the CommandLineParser.

__init__(actions)
actions: Tuple[ActionMetaData, ...]

The action meta data used to parse and print help.

property actions_by_name: Dict[str, ActionMetaData]
deallocate()[source]

Deallocate all resources for this instance.

property first_pass_actions: Tuple[ActionMetaData, ...]
property first_pass_by_option: Dict[str, ActionMetaData]
property first_pass_options: Tuple[OptionMetaData, ...]
property second_pass_actions: Tuple[ActionMetaData, ...]
exception zensols.cli.command.CommandLineConfigError[source]

Bases: Exception

Programmer error for command line parser configuration errors.

__module__ = 'zensols.cli.command'
__weakref__

list of weak references to the object

exception zensols.cli.command.CommandLineError[source]

Bases: ApplicationError

Raised when command line parameters can not be parsed.

__annotations__ = {}
__module__ = 'zensols.cli.command'
class zensols.cli.command.CommandLineParser(config, version='v0', default_action=None, force_default=False, application_doc=None, usage_config=<factory>)[source]

Bases: Deallocatable, Dictable

Parse the command line. The parser iterates twice over the command line:

  1. The first pass parses only first pass actions (ActionMetaData.first_pass). This step also is used to discover the mnemonic/name of the single second pass action.

  2. The second pass parse parses only a single action that is given on the command line.

The name is given as a mnemonic of the action, unless there is only one second pass action given, in which case all options and usage are given at the top level and a mnemonic is not needed nor parsed.

:see ActionMetaData.first_pass

__init__(config, version='v0', default_action=None, force_default=False, application_doc=None, usage_config=<factory>)
application_doc: str = None

The program documentation to use when it can not be deduced from the action.

config: CommandLineConfig

Configures the command line parser with the action meta data.

deallocate()[source]

Deallocate all resources for this instance.

default_action: str = None

The default mnemonic use when the user does not supply one.

error(msg)[source]

Print a usage with the error message and exit the program as fail.

force_default: str = False

Choice of action becomes ambiguous when the positional arguments are given and the action name matches the argument. An error is raised when the application is configured in this way.

When this attribute is True, the command parsing will insert the default action when the first non-option isn’t found as an action. However, this leads to the mentioned ambiguouity and is inefficient.

parse(args)[source]

Parse command line arguments.

Parameters:

args (List[str]) – the arguments given on the command line; which is usually sys.args[1:]

Return type:

CommandActionSet

usage_config: UsageConfig

Configuraiton information for the command line help.

version: str = 'v0'

The version of the application, which is used in the help and the --version switch.

write_help(writer=None, include_actions=True, action_metas=None, action_format='long')[source]

Write the usage information and help text.

Parameters:
  • writer (TextIOBase) – the data sync, or sys.stdout if None

  • include_actions (bool) – if True write each actions’ usage as well

  • actions – the list of actions to output, or None for all

  • action_format (str) – the action format, either short or long

zensols.cli.harness module

Main entry point for applications that use the app API.

class zensols.cli.harness.CliHarness(src_dir_name=None, package_resource='app', app_config_resource='resources/app.conf', app_config_context=<factory>, root_dir=None, app_factory_class=<class 'zensols.cli.app.ApplicationFactory'>, relocate=True, proto_args=<factory>, proto_factory_kwargs=<factory>, proto_header=None, log_format='%(asctime)-15s [%(name)s] %(message)s', no_exit=False)[source]

Bases: object

A utility class to automate the creation of execution of the Application from either the command line or a Python REPL.

__init__(src_dir_name=None, package_resource='app', app_config_resource='resources/app.conf', app_config_context=<factory>, root_dir=None, app_factory_class=<class 'zensols.cli.app.ApplicationFactory'>, relocate=True, proto_args=<factory>, proto_factory_kwargs=<factory>, proto_header=None, log_format='%(asctime)-15s [%(name)s] %(message)s', no_exit=False)
static add_sys_path(to_add)[source]

Add to the Python system path if not already.

Parameters:

to_add (Union[str, Path]) – the path to test and add

app_config_context: Dict[str, Dict[str, str]]

More context given to the application context on app creation.

app_config_resource: Union[str, TextIOBase] = 'resources/app.conf'

The relative resource path to the application’s context. If set as an instance of io.TextIOBase then read from that resource instead of trying to find a resource file.

See:

ApplicationFactory.app_config_resource

app_factory_class

The application factory used to create thye application.

alias of ApplicationFactory

configure_logging(*args, **kwargs)[source]

Convenience method to configure the logging package system for early stage (bootstrap) debugging. However, the “right” way to configure logging is in the application configuration.

The arguments provided are given to the initializer of LogConfigurator, which is then used to configure the logging system.

create_application_factory(args=(), **factory_kwargs)[source]

Create and return the application factory.

Parameters:
Return type:

ApplicationFactory

Returns:

the application factory on which to call ApplicationFactory.invoke()

execute(args=None)[source]

Invoke the application with command line with arguments from other Python programs or the REPL.

Parameters:

args (Union[List[str], str]) – the command line arguments without the first argument (the program name)

Return type:

Optional[ApplicationResult]

Returns:

the application results if it did not try to exit

get_application(args=None, throw=True, app_section='app')[source]

Get the application from the configuration factory. For this to work, the app_section section must not be in the cleanups. Otherwise the framework will remove the section before the call to the configuration factory to create it.

Parameters:
  • args (Union[List[str], str]) – additional argument to give to the pseudo command line (i.e. -c <configuration file>)

  • throw (bool) – whether to throw exceptions raised during executing the application; if False then return an ApplicationFailure

  • app_section (str) – the name of the section that defines the app to get

Return type:

Union[Application, ApplicationFailure]

Returns:

the application instance specified in the app_section

get_config_factory(args=None, throw=True)[source]

The application configuration factory.

Parameters:
  • args (Union[List[str], str]) – additional argument to give to the pseudo command line (i.e. -c <configuration file>)

  • throw (bool) – whether to throw exceptions raised during executing the application; if False then return an ApplicationFailure

Return type:

Union[ConfigFactory, ApplicationFailure]

Returns:

the configuration factory used to create the application environment and application config or the ApplicationFailure if throw is True

get_instance(args='', **factory_kwargs)[source]

Create the invokable instance of the application.

Parameters:
  • args (Union[List[str], str]) – the arguments to the application not including the program name (as it makes no sense in the context of this call); if this is a string, it will be converted to a list by splitting on whitespace; this defaults to the output of _get_default_args()

  • factory_kwargs (Dict[str, Any]) – arguments passed to ApplicationFactory

See:

ApplicationFactory.get_instance()

Return type:

Union[Any, ApplicationFailure]

invoke(args=['/Users/landes/opt/lib/python/bin/sphinx-build', '-M', 'html', '/Users/landes/view/pygh/util/target/doc/src', '/Users/landes/view/pygh/util/target/doc/build'], **factory_kwargs)[source]

Invoke the application using the standard command line arguments. This is called from command line entry points. To invoke from Python use execute().

Parameters:
  • args (List[str]) – all command line arguments including the program name

  • factory_kwargs (Dict[str, Any]) – arguments given to the command line factory

Return type:

ApplicationResult

Returns:

the application results

property invoke_method: str

Return how the program was invoked.

Returns:

one of eval for re-evaluating the file, repl from the REPL or main for invocation from the main command line

log_format: str = '%(asctime)-15s [%(name)s] %(message)s'

The log formatting used in configure_logging().

no_exit: bool = False

If True do not exist the program when SystemExit is raised.

package_resource: Union[str, PackageResource] = 'app'

The application package resource.

See:

ApplicationFactory.package_resource

proto(args=None)[source]

Invoke the prototype using proto_args and proto_factory_kwargs.

Parameters:

args (Union[List[str], str]) – the command line arguments without the first argument (the program name)

Return type:

Optional[ApplicationResult]

Returns:

the application results if it did not try to exit

proto_args: Union[str, List[str]]

The command line arguments.

proto_factory_kwargs: Dict[str, Any]

Factory keyword arguments given to the ApplicationFactory.

proto_header: str = None

Printed for each invocation of the prototype command line. This is handy when running in environments such as Emacs REPL to clarify the invocation method.

relocate: bool = True

Whether or not to make source_dir_name and app_config_resource relative to root_dir (when non-None). This should be set to False when used to create an application that is installed (i.e. with pip).

root_dir: Path = None

The entry point directory where to make all files relative. If not given, it is resolved from the parent of the entry point program path in the (i.e. sys.argv) arguments.

run()[source]

The command line script (i.e. model harness scripts) entry point.

Return type:

Optional[ActionResult]

Returns:

the application results if it did not exit

src_dir_name: str = None

The directory (relative to root_dir to add to the Python path containing the source files.

class zensols.cli.harness.ConfigFactoryAccessor(config_factory)[source]

Bases: object

Return an instance from a ConfigFactory, which is useful for creating harnesses and accessing application context configured instances.

Important: if configured to access an application class in the application context, you will need to remove the entry from the removes in the cli seciton of the app.conf file.

CLI_META = {'is_usage_visible': False, 'mnemonic_overrides': {'access': 'add_ConfigFactoryAccessor_to_app_config'}, 'option_includes': {}}
LONG_NAME = 'add_ConfigFactoryAccessor_to_app_config'

The long name of the first pass option to denote the application is to be returned in a pragmatic context as a client to CliHarness.

See:

ListActions

__init__(config_factory)
access()[source]

Return the configuration factory.

Return type:

ConfigFactory

config_factory: ConfigFactory

The parent configuration factory that is returned when accessed.

class zensols.cli.harness.ConfigurationImporterCliHarness(src_dir_name=None, package_resource='app', app_config_resource='resources/app.conf', app_config_context=<factory>, root_dir=None, app_factory_class=<class 'zensols.cli.app.ApplicationFactory'>, relocate=True, proto_args=<factory>, proto_factory_kwargs=<factory>, proto_header=None, log_format='%(asctime)-15s [%(name)s] %(message)s', no_exit=False, config_path=None)[source]

Bases: CliHarness

A harness that adds command line arguments for the configuration file when they are available. It does this by finding an instance of ConfigurationImporter in the command line metadata. When it finds it, if not set from the given set of arguments it:

  1. Uses config_path

2. Gets the path from the environment variable set using ConfigurationImporter

Implementation note: One disadvantage to using this over CliHarness is that it has to parse the application configuration and create the application twice. This can slow the start of the application and is noticable for larger configurations.

__init__(src_dir_name=None, package_resource='app', app_config_resource='resources/app.conf', app_config_context=<factory>, root_dir=None, app_factory_class=<class 'zensols.cli.app.ApplicationFactory'>, relocate=True, proto_args=<factory>, proto_factory_kwargs=<factory>, proto_header=None, log_format='%(asctime)-15s [%(name)s] %(message)s', no_exit=False, config_path=None)
config_path: Union[str, Path] = None
get_instance(args=None, **factory_kwargs)[source]

Create the invokable instance of the application.

Parameters:
  • args (Union[List[str], str]) – the arguments to the application not including the program name (as it makes no sense in the context of this call); if this is a string, it will be converted to a list by splitting on whitespace; this defaults to the output of _get_default_args()

  • factory_kwargs (Dict[str, Any]) – arguments passed to ApplicationFactory

See:

ApplicationFactory.get_instance()

Return type:

Any

invoke(args=['/Users/landes/opt/lib/python/bin/sphinx-build', '-M', 'html', '/Users/landes/view/pygh/util/target/doc/src', '/Users/landes/view/pygh/util/target/doc/build'], **factory_kwargs)[source]

Invoke the application using the standard command line arguments. This is called from command line entry points. To invoke from Python use execute().

Parameters:
  • args (List[str]) – all command line arguments including the program name

  • factory_kwargs (Dict[str, Any]) – arguments given to the command line factory

Return type:

Any

Returns:

the application results

class zensols.cli.harness.NotebookHarness(src_dir_name=None, package_resource='app', app_config_resource='resources/app.conf', app_config_context=<factory>, root_dir=None, app_factory_class=<class 'zensols.cli.app.ApplicationFactory'>, relocate=True, proto_args=<factory>, proto_factory_kwargs=<factory>, proto_header=None, log_format='%(asctime)-15s [%(name)s] %(message)s', no_exit=False, factory_kwargs=<factory>)[source]

Bases: CliHarness

A harness used in Jupyter notebooks. This class has default configuration useful to having a single directory with one or more notebooks off the project root ditectory.

For this reason root_dir is the parent directory, which is used to add src_dir_name to the Python path.

__init__(src_dir_name=None, package_resource='app', app_config_resource='resources/app.conf', app_config_context=<factory>, root_dir=None, app_factory_class=<class 'zensols.cli.app.ApplicationFactory'>, relocate=True, proto_args=<factory>, proto_factory_kwargs=<factory>, proto_header=None, log_format='%(asctime)-15s [%(name)s] %(message)s', no_exit=False, factory_kwargs=<factory>)
factory_kwargs: Dict[str, Any]

Arguments given to the factory when creating new application instances with __call__().

reset()[source]

Reset the notebook and recreate all resources.

static set_browser_width(width=95)[source]

Use the entire width of the browser to create more real estate.

Parameters:

width (int) – the width as a percent ([0, 100]) to use as the width in the notebook

zensols.cli.meta module

Domain classes for parsing the command line.

class zensols.cli.meta.ActionMetaData(name=None, doc=None, options=<factory>, positional=<factory>, first_pass=False, is_usage_visible=True)[source]

Bases: PersistableContainer, Dictable

An action represents a link between a command line mnemonic action and a method on a class to invoke.

__init__(name=None, doc=None, options=<factory>, positional=<factory>, first_pass=False, is_usage_visible=True)
doc: str = None

A short human readable documentation string used in the usage.

first_pass: bool = False

If True this is a first pass action that is used with no mnemonic. Examples include the -w/--whine logging level, which applies to the entire application and can be configured in a separate class/process from the main single action given as a mnemonic on the command line.

is_usage_visible: bool = True

Whether to display the action in the help usage. Applications such as ConfigFactoryAccessor, which is only useful with a programatic usage, is an example of where this is used.

name: str = None

The name of the action, which is also the mnemonic used on the command line.

options: Tuple[OptionMetaData, ...]

The command line options for the action.

property options_by_dest: Dict[str, OptionMetaData]
positional: Tuple[PositionalMetaData, ...]

The positional arguments expected for the action.

exception zensols.cli.meta.ApplicationError[source]

Bases: ActionCliError

Thrown for any application error that should result in a user error rather than produce a full stack trace.

__annotations__ = {}
__module__ = 'zensols.cli.meta'
class zensols.cli.meta.ApplicationFailure(exception=None, thrower=None, traceback=None, message=None)[source]

Bases: Failure, Dictable

Contains information for application invocation failures used by programatic methods.

__init__(exception=None, thrower=None, traceback=None, message=None)
raise_exception()[source]

Raise the contained exception. The exception will include message if available.

Throws ApplicationError:

every time for the contained exception

class zensols.cli.meta.OptionFactory[source]

Bases: object

Creates commonly used options.

classmethod config_file(**kwargs)[source]

A subordinate file based configuration option.

Return type:

OptionMetaData

classmethod directory(name, short_name, **kwargs)[source]

A directory Path option.

classmethod dry_run(**kwargs)[source]

A boolean dry run option.

Return type:

OptionMetaData

classmethod file(name, short_name, **kwargs)[source]

A file Path option.

class zensols.cli.meta.OptionMetaData(long_name, short_name=None, dest=None, dtype=<class 'str'>, choices=None, default=None, doc=None, metavar=None)[source]

Bases: PersistableContainer, Dictable, _MetavarFormatter

A command line option.

DATA_TYPES = frozenset({<class 'bool'>, <class 'dict'>, <class 'float'>, <class 'int'>, <class 'list'>, <class 'pathlib.Path'>, <class 'str'>, <class 'zensols.introspect.intsel.IntegerSelection'>})

Supported data types.

__init__(long_name, short_name=None, dest=None, dtype=<class 'str'>, choices=None, default=None, doc=None, metavar=None)
choices: Tuple[str, ...] = None

The constant list of choices when dtype is list. Note that this class is a tuple so instances are hashable in ActionCli.

create_option()[source]

Add the option to an option parser.

Parameters:

parser – the parser to populate

Return type:

Option

default: str = None

The default value of the option.

property default_str: str

Get the default as a string usable in printing help and as a default using the optparse.OptionParser class.

dest: str = None

The the field/parameter name used to on the target class.

doc: str = None

The document string used in the command line help.

dtype

The data type of the option (i.e. str).

Other types include: int, :class`float`, bool, list (for choice), or patlib.Path for files and directories.

alias of str

long_name: str

The long name of the option (i.e. --config).

property long_option: str

The long option string with dashes.

metavar: str = None

Used in the command line help for the type of the option.

short_name: str = None

The short name of the option (i.e. -c).

property short_option: str

The short option string with dash.

property shortest_option: str

The shortest option (or long if no short option) with dash.

write(depth=0, writer=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Write this instance as either a Writable or as a Dictable. If class attribute _DICTABLE_WRITABLE_DESCENDANTS is set as True, then use the write() method on children instead of writing the generated dictionary. Otherwise, write this instance by first creating a dict recursively using asdict(), then formatting the output.

If the attribute _DICTABLE_WRITE_EXCLUDES is set, those attributes are removed from what is written in the write() method.

Note that this attribute will need to be set in all descendants in the instance hierarchy since writing the object instance graph is done recursively.

Parameters:
  • depth (int) – the starting indentation depth

  • writer (TextIOBase) – the writer to dump the content of this writable

class zensols.cli.meta.PositionalMetaData(name, dtype=<class 'str'>, doc=None, choices=None, metavar=None)[source]

Bases: Dictable, _MetavarFormatter

A command line required argument that has no option switches.

__init__(name, dtype=<class 'str'>, doc=None, choices=None, metavar=None)
choices: Tuple[str, ...] = None

The constant list of choices when dtype is list. Note that this class is a tuple so instances are hashable in ActionCli.

doc: str = None

The documentation of the positional metadata or None if missing.

dtype

The type of the positional argument.

See:

Option.dtype

alias of str

metavar: str = None

Used in the command line help for the type of the option.

name: str

The name of the positional argument. Used in the documentation and when parsing the type.

zensols.cli.meta.apperror(method=None, *, exception=<class 'Exception'>)[source]

A decorator that rethrows any method’s exception as an ApplicationError. This is helpful for application classes that should print a usage rather than an exception stack trace.

An optional exception parameter can be provided so the exception is rethrown for only certain caught exceptions.

zensols.cli.notebook module

zensols.cli.usage module

Utility classes to write command line help.

see:

UsageActionOptionParser

class zensols.cli.usage.UsageActionOptionParser(actions, options, usage_config, doc=None, default_action=None, *args, **kwargs)[source]

Bases: OptionParser

Implements a human readable implementation of print_help() for action based command line handlers.

Each action is described with the full documentation with --help. However, the short option version (-h) creates a much (GNU style) summarization of the command and actions.

If an action or several actions are given with either help flag, only that action usage and documentation is printed.

Implementation note: we have to extend OptionParser since the -h option invokes the print help behavior and then exists printing the second pass action options. Instead, we look for the help option in the first pass, print help with the correction options, then exit.

__init__(actions, options, usage_config, doc=None, default_action=None, *args, **kwargs)[source]
print_help(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, include_actions=True, action_metas=None, action_format=False)[source]

Write the usage information and help text.

Parameters:
  • include_actions (bool) – if True write each actions’ usage as well

  • actions – the list of actions to output, or None for all

  • action_format (str) – the action format, either short or long

class zensols.cli.usage.UsageConfig(width=None, max_first_col=0.4, max_metavar_len=0.15, max_default_len=0.1, left_indent=2, inter_col_space=2, sort_actions=False, doc=None)[source]

Bases: Dictable

Configuraiton information for the command line help.

__init__(width=None, max_first_col=0.4, max_metavar_len=0.15, max_default_len=0.1, left_indent=2, inter_col_space=2, sort_actions=False, doc=None)
doc: str = None

Overrides the application help documentation.

inter_col_space: int = 2

The number of spaces between all three columns.

left_indent: int = 2

The number of left spaces for the option and positional arguments.

max_default_len: Union[float, int] = 0.1

Max length in characters of the default value.

max_first_col: Union[float, int] = 0.4

Maximum width of the first column. If this is a float, then it is computed as a percentage of the terminal width.

max_metavar_len: Union[float, int] = 0.15

Max length of the option type.

sort_actions: bool = False

If True sort mnemonic output.

width: int = None

The max width to print help.

zensols.cli.util module

Utility classes for command line functionality.

class zensols.cli.util.DocUtil[source]

Bases: object

A utility class to format API documentation parsed from the class.

classmethod module_name()[source]

Return the config (parent) module name.

Return type:

str

static normalize(text)[source]

Lower case and remove punctuation.

Return type:

str

static unnormalize(text)[source]

Return a normalized doc string back to a (more) typical English syntax.

Return type:

str

Module contents

Modules include a tight coupling between the command line and configure driven applications.

exception zensols.cli.ActionCliError[source]

Bases: APIError

Thrown for all command line interface errors.

__annotations__ = {}
__module__ = 'zensols.cli'