zensols.cli package¶
Subpackages¶
- zensols.cli.lib namespace
- Submodules
- zensols.cli.lib.config module
ConfigurationImporter
ConfigurationImporter.CLI_META
ConfigurationImporter.CONFIG_PATH_FIELD
ConfigurationImporter.ENVIRON_VAR_REGEX
ConfigurationImporter.IMPORT_TYPE
ConfigurationImporter.__init__()
ConfigurationImporter.arguments
ConfigurationImporter.cache_path
ConfigurationImporter.config
ConfigurationImporter.config_path
ConfigurationImporter.config_path_environ_name
ConfigurationImporter.config_path_option_name
ConfigurationImporter.debug
ConfigurationImporter.default
ConfigurationImporter.expect
ConfigurationImporter.get_environ_path()
ConfigurationImporter.get_environ_var_from_app()
ConfigurationImporter.merge()
ConfigurationImporter.name
ConfigurationImporter.section
ConfigurationImporter.type
ConfigurationOverrider
ConfigurationOverrider.CLI_META
ConfigurationOverrider.OVERRIDE_FIELD
ConfigurationOverrider.__init__()
ConfigurationOverrider.config
ConfigurationOverrider.disable
ConfigurationOverrider.get_configurable()
ConfigurationOverrider.merge()
ConfigurationOverrider.option_sep_regex
ConfigurationOverrider.override
- zensols.cli.lib.log module
LogConfigurator
LogConfigurator.CLI_META
LogConfigurator.__init__()
LogConfigurator.config()
LogConfigurator.config_file
LogConfigurator.debug
LogConfigurator.default_app_level
LogConfigurator.default_level
LogConfigurator.format
LogConfigurator.level
LogConfigurator.log_name
LogConfigurator.loggers
LogConfigurator.reset()
LogConfigurator.set_format()
LogLevel
- zensols.cli.lib.package module
- zensols.cli.lib.support module
CacheClearer
Cleaner
ConfigFormat
DryRunApplication
EditConfiguration
ExportEnvironment
ExportFormat
ListActions
ListFormat
ProgramNameConfigurator
ShowConfiguration
ShowConfiguration.CLI_META
ShowConfiguration.EVAL_NAME
ShowConfiguration.OUTPUT_FORMAT
ShowConfiguration.OUTPUT_PATH
ShowConfiguration.SECTION_NAME
ShowConfiguration.__init__()
ShowConfiguration.config_factory
ShowConfiguration.config_output_format
ShowConfiguration.config_output_path
ShowConfiguration.evaluate
ShowConfiguration.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
,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 likePackageInfoImporter
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
. AnActionCli
is created from the configuration given by the section. Optionally, another section usingdecorator_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:
- 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
CommandLineParser
to create instances of the application. Each action CLI has a collection ofActionMetaData
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 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:
ActionCliError
Raised by
ActionCliManager
for any problems creatingActionCli
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)¶
- 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:
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 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:
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 (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:
PersistableContainer
Boots the application context from the command line. This first loads resource
resources/app.conf
from this package, then addsapp_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 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
Exception
and this instance as a paramters to handle the error. This can be set toApplicationFailure
for 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 againstException
andSystemExit
. 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
ApplicationFailure
ifException
orSystemExit
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 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
reload
inImportConfigFactory
.- See:
_create_config_factory()
- 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 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:
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.
- 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. Propertiesfirst_pass_actions
andsecond_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.
- 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]¶
- 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:
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
--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, orsys.stdout
ifNone
include_actions (
bool
) – ifTrue
write each actions’ usage as wellactions – the list of actions to output, or
None
for allaction_format (
str
) – the action format, eithershort
orlong
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)¶
-
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.
- 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_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; ifFalse
then return anApplicationFailure
app_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
ApplicationFailure
ifthrow
isTrue
- 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/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()
.
- property invoke_method: str¶
Return how the program was invoked.
- Returns:
one of
eval
for re-evaluating the file,repl
from the REPL ormain
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 whenSystemExit
is raised.
-
package_resource:
Union
[str
,PackageResource
] = 'app'¶ The application package resource.
- proto(args=None)[source]¶
Invoke the prototype using
proto_args
andproto_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_name
andapp_config_resource
relative toroot_dir
(when non-None
). This should be set toFalse
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.
- 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 theapp.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:
- __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, 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: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)¶
- 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/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()
.
- 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 addsrc_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>)¶
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)¶
-
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.
-
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]¶
-
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:
object
Creates 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
,_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
islist
. 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.OptionParser
class.
- dtype¶
The data type of the option (i.e.
str
).Other types include:
int
, :class`float`,bool
,list
(for choice), orpatlib.Path
for 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
Writable
or as aDictable
. If class attribute_DICTABLE_WRITABLE_DESCENDANTS
is set asTrue
, then use thewrite()
method on children instead of writing the generated dictionary. Otherwise, write this instance by first creating adict
recursively usingasdict()
, then formatting the output.If the attribute
_DICTABLE_WRITE_EXCLUDES
is 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
,_MetavarFormatter
A 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:
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.
- 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)¶
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.