zensols.cli package¶
Subpackages¶
- zensols.cli.lib namespace
- Submodules
- zensols.cli.lib.config module
ConfigurationImporterConfigurationImporter.CLI_METAConfigurationImporter.CONFIG_PATH_FIELDConfigurationImporter.ENVIRON_SHARED_NAMEConfigurationImporter.ENVIRON_VAR_REGEXConfigurationImporter.IMPORT_TYPEConfigurationImporter.__init__()ConfigurationImporter.argumentsConfigurationImporter.cache_pathConfigurationImporter.configConfigurationImporter.config_pathConfigurationImporter.config_path_environ_nameConfigurationImporter.config_path_option_nameConfigurationImporter.debugConfigurationImporter.defaultConfigurationImporter.expectConfigurationImporter.get_environ_path()ConfigurationImporter.get_environ_var_from_app()ConfigurationImporter.merge()ConfigurationImporter.nameConfigurationImporter.sectionConfigurationImporter.type
ConfigurationOverriderConfigurationOverrider.CLI_METAConfigurationOverrider.OVERRIDE_FIELDConfigurationOverrider.__init__()ConfigurationOverrider.configConfigurationOverrider.disableConfigurationOverrider.get_configurable()ConfigurationOverrider.merge()ConfigurationOverrider.option_sep_regexConfigurationOverrider.override
- zensols.cli.lib.log module
LogConfiguratorLogConfigurator.CLI_METALogConfigurator.__init__()LogConfigurator.config()LogConfigurator.config_fileLogConfigurator.debugLogConfigurator.default_app_levelLogConfigurator.default_levelLogConfigurator.formatLogConfigurator.levelLogConfigurator.log_nameLogConfigurator.loggersLogConfigurator.reset()LogConfigurator.set_format()LogConfigurator.skip_config
LogLevel
- zensols.cli.lib.package module
- zensols.cli.lib.support module
CacheClearerCleanerConfigFormatDryRunApplicationEditConfigurationExportEnvironmentExportFormatListActionsListFormatProgramNameConfiguratorShowConfigurationShowConfiguration.CLI_METAShowConfiguration.EVAL_NAMEShowConfiguration.OUTPUT_FORMATShowConfiguration.OUTPUT_PATHShowConfiguration.SECTION_NAMEShowConfiguration.__init__()ShowConfiguration.config_factoryShowConfiguration.config_output_formatShowConfiguration.config_output_pathShowConfiguration.evaluateShowConfiguration.show_config()
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,DictableA 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 likePackageInfoImporterto 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
OptionMetaDatawhere 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,DictableManages instances of
ActionCli. AnActionCliis created from the configuration given by the section. Optionally, another section usingdecorator_section_formatwill 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:
- See:
- 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
CommandLineParserto create instances of the application. Each action CLI has a collection ofActionMetaDatainstances.- 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
ActionMetaDatainstances, 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 mergecli_meta (
Dict[str,Any]) – the metadata identified by theCLASS_META_ATTRIBUTE
- property config: Configurable¶
- default_action: str = None¶
The default mnemonic use when the user does not supply one.
- 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.
- usage_config: UsageConfig¶
Configuraiton information for the command line help.
- exception zensols.cli.action.ActionCliManagerError[source]¶
Bases:
ActionCliErrorRaised by
ActionCliManagerfor any problems creatingActionCliinstances.- __module__ = 'zensols.cli.action'¶
- class zensols.cli.action.ActionCliMethod(action_meta_data, method)[source]¶
Bases:
DictableA “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,DictableAn invokable action from the command line the
Applicationclass. 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)¶
- 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.
- 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.
- class zensols.cli.app.ActionResult(action, instance, result)[source]¶
Bases:
DictableThe results of a single method call to an
Actioninstance. There is one of these per action (both first and second pass) provided inApplicationResult.- __init__(action, instance, result)¶
- action: Action¶
The action that was used to generate the result.
- instance: Any¶
The application instance.
- result: Any¶
The results returned from the invocation on the application instance.
- class zensols.cli.app.Application(config_factory, factory, actions)[source]¶
Bases:
DictableAn 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 (seesecond_pas_action).- __init__(config_factory, factory, actions)¶
- actions: Tuple[Action, ...]¶
The list of actions to invoke in order.
- 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.
- 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:
PersistableContainerBoots the application context from the command line. This first loads resource
resources/app.conffrom this package, then addsapp_config_resourcefrom 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 ofio.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:
- 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
Exceptionand this instance as a paramters to handle the error. This can be set toApplicationFailurefor programatic entry to this class (seeCliHarness).
- 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:
- 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:
- Returns:
the result of the second pass action
- invoke_protect(args=None)[source]¶
Same as
invoke(), but protect againstExceptionandSystemExit. 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:
- Returns:
the result of the second pass action or an
ApplicationFailureifExceptionorSystemExitis 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 inImportConfigFactory.- 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
reloadinImportConfigFactory.- See:
_create_config_factory()
- class zensols.cli.app.ApplicationObserver[source]¶
Bases:
ABCExtended 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:
DictableA container class of the results of an application invocation with
Application.invoke(). This is keyed by index of the actions given inactions.- __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.
zensols.cli.command module¶
Classes to parse command line arguments.
- class zensols.cli.command.CommandAction(meta_data, options, positional)[source]¶
Bases:
DictableThe output of the
CommandLineParserfor each parsed action.- __init__(meta_data, options, positional)¶
-
meta_data:
ActionMetaData¶ The action parsed from the command line.
- class zensols.cli.command.CommandActionSet(actions)[source]¶
Bases:
Deallocatable,DictableThe actions that are parsed by
CommandLineParseras the output of the parse phase. This is indexable by command action name and iterable across all actions. Propertiesfirst_pass_actionsandsecond_pass_actiongive 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.
- 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,DictableGiven 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]¶
- 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:
ExceptionProgrammer 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:
ApplicationErrorRaised 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,DictableParse the command line. The parser iterates twice over the command line:
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.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.
-
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.
-
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
--versionswitch.
- 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, orsys.stdoutifNoneinclude_actions (
bool) – ifTruewrite each actions’ usage as wellactions – the list of actions to output, or
Nonefor allaction_format (
str) – the action format, eithershortorlong
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, sys_path=None)[source]¶
Bases:
objectA utility class to automate the creation of execution of the
Applicationfrom 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, sys_path=None)¶
- static add_sys_path(to_add, insert_index=None)[source]¶
Add to the Python system path if not already.
- Parameters:
to_add (
Union[str,Path]) – the path or string path list separated byos.pathsep(such as:) and may have user home names (~)insert_index (
int) – where in the path to add orNoneto add to the end
-
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.TextIOBasethen read from that resource instead of trying to find a resource file.
- 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:
- 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.
- get_application(args=None, throw=True, app_section='app')[source]¶
Get the application from the configuration factory. For this to work, the
app_sectionsection 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; ifFalsethen return anApplicationFailureapp_section (
str) – the name of the section that defines the app to get
- Return type:
- Returns:
the application instance specified in the
app_section
- get_config_factory(args=None, throw=True)[source]¶
The application configuration factory.
- Parameters:
- Return type:
- Returns:
the configuration factory used to create the application environment and application config or the
ApplicationFailureifthrowisTrue
- 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 toApplicationFactory
- See:
- Return type:
- invoke(args=['/Users/landes/opt/lib/pixi/envs/zensols_relpo/bin/sphinx-build', '-M', 'html', '/Users/landes/view/pygh/util/target/doc/stage', '/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().
- property invoke_method: str¶
Return how the program was invoked.
- Returns:
one of
evalfor re-evaluating the file,replfrom the REPL ormainfor 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
Truedo not exist the program whenSystemExitis raised.
-
package_resource:
Union[str,PackageResource] = 'app'¶ The application package resource.
- proto(args=None)[source]¶
Invoke the prototype using
proto_argsandproto_factory_kwargs.
-
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_nameandapp_config_resourcerelative toroot_dir(when non-None). This should be set toFalsewhen 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:
- Returns:
the application results if it did not exit
-
src_dir_name:
str= None¶ The directory (relative to
root_dirto add to the Python path containing the source files.
-
sys_path:
str= None¶ Paths separated by
os.pathsep(such as:) to add to thesys.path(PYTHONPATH). These paths are added to the beginning of the system path.
- class zensols.cli.harness.ConfigFactoryAccessor(config_factory)[source]¶
Bases:
objectReturn 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
cliseciton of theapp.conffile.- 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:
- __init__(config_factory)¶
-
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, sys_path=None, config_path=None)[source]¶
Bases:
CliHarnessA harness that adds command line arguments for the configuration file when they are available. It does this by finding an instance of
ConfigurationImporterin the command line metadata. When it finds it, if not set from the given set of arguments it:Uses
config_path
2. Gets the path from the environment variable set using
ConfigurationImporterImplementation note: One disadvantage to using this over
CliHarnessis 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, sys_path=None, config_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 toApplicationFactory
- See:
- Return type:
- invoke(args=['/Users/landes/opt/lib/pixi/envs/zensols_relpo/bin/sphinx-build', '-M', 'html', '/Users/landes/view/pygh/util/target/doc/stage', '/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().
- 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, sys_path=None, factory_kwargs=<factory>)[source]¶
Bases:
CliHarnessA 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_diris the parent directory, which is used to addsrc_dir_nameto 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, sys_path=None, factory_kwargs=<factory>)¶
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,DictableAn 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)¶
-
first_pass:
bool= False¶ If
Truethis is a first pass action that is used with no mnemonic. Examples include the-w/--whinelogging 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.
-
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:
ActionCliErrorThrown 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]¶
-
Contains information for application invocation failures used by programatic methods.
- __init__(exception=None, thrower=None, traceback=None, message=None)¶
- class zensols.cli.meta.OptionFactory[source]¶
Bases:
objectCreates commonly used options.
- classmethod config_file(**kwargs)[source]¶
A subordinate file based configuration option.
- Return type:
- 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,_MetavarFormatterA 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
dtypeislist. Note that this class is a tuple so instances are hashable inActionCli.
- create_option()[source]¶
Add the option to an option parser.
- Parameters:
parser – the parser to populate
- Return type:
- property default_str: str¶
Get the default as a string usable in printing help and as a default using the
optparse.OptionParserclass.
- dtype¶
The data type of the option (i.e.
str).Other types include:
int, :class`float`,bool,list(for choice), orpatlib.Pathfor files and directories.alias of
str
- write(depth=0, writer=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Write this instance as either a
Writableor as aDictable. If class attribute_DICTABLE_WRITABLE_DESCENDANTSis set asTrue, then use thewrite()method on children instead of writing the generated dictionary. Otherwise, write this instance by first creating adictrecursively usingasdict(), then formatting the output.If the attribute
_DICTABLE_WRITE_EXCLUDESis set, those attributes are removed from what is written in thewrite()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 depthwriter (
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,_MetavarFormatterA command line required argument that has no option switches.
- __init__(name, dtype=<class 'str'>, doc=None, choices=None, metavar=None)¶
- 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.
- class zensols.cli.usage.UsageActionOptionParser(actions, options, usage_config, doc=None, default_action=None, *args, **kwargs)[source]¶
Bases:
OptionParserImplements 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
OptionParsersince the-hoption 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.
- 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:
DictableConfiguraiton 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)¶
zensols.cli.util module¶
Utility classes for command line functionality.
Module contents¶
Modules include a tight coupling between the command line and configure driven applications.