API Reference¶
Running functions¶
- clize.run(*fn, args=None, catch=(), exit=True, out=None, err=None, **kwargs)[source]¶
Runs a function or CLI object with
args, prints the return value if not None, or catches the given exception types as well asclize.UserErrorand prints their string representation, then exit with the appropriate status code.- Parameters
args (sequence) – The arguments to pass the CLI, for instance
('./a_script.py', 'spam', 'ham'). If unspecified, usessys.argv.catch (sequence of exception classes) – Catch these exceptions and print their string representation rather than letting Python print an uncaught exception traceback.
exit (bool) – If true, exit with the appropriate status code once the function is done.
out (file) – The file in which to print the return value of the command. If unspecified, uses
sys.stdouterr (file) – The file in which to print any exception text. If unspecified, uses
sys.stderr.
- class clize.Clize(fn=None, **kwargs)[source]¶
Wraps a function into a CLI object that accepts command-line arguments and translates them to match the wrapped function’s parameters.
- Parameters
alt (sequence) – Alternate actions the CLI will handle.
help_names (sequence of strings) – Names to use to trigger the help.
helper_class (a type like
ClizeHelp) – A callable to produce a helper object to be used when the help is triggered. If unset, usesClizeHelp.hide_help (bool) – Mark the parameters used to trigger the help as undocumented.
Parser¶
- class clize.parser.CliSignature(parameters)[source]¶
A collection of parameters that can be used to translate CLI arguments to function arguments.
- Parameters
parameters (iterable) – The parameters to use.
- converter = clize.parser.default_converter¶
The converter used by default in case none is present in the annotations.
- parameters¶
An ordered dict of all parameters of this cli signature.
- positional¶
List of positional parameters.
- alternate¶
List of parameters that initiate an alternate action.
- aliases = {}¶
Maps parameter names to
NamedParameterinstances.
- required = set()¶
A set of all required parameters.
- clize.parser.parameter_converter(obj=None, *, name=None)[source]¶
Decorates a callable to be interpreted as a parameter converter when passed as an annotation.
It will be called with an
inspect.Parameterobject and a sequence of objects passed as annotations, without the parameter converter itself. It is expected to return aclize.parser.Parameterinstance orParameter.IGNORE.
- clize.parser.default_converter(param, annotations, *, type_annotation)¶
The default parameter converter. It is described in detail in The default parameter converter.
- clize.parser.use_class(*, name=None, pos=<function unimplemented_parameter at 0x7febf3781ca0>, varargs=<function unimplemented_parameter at 0x7febf3781ca0>, named=<function unimplemented_parameter at 0x7febf3781ca0>, varkwargs=<function unimplemented_parameter at 0x7febf3781ca0>, kwargs={})[source]¶
Creates a parameter converter similar to the default converter that picks one of 4 factory functions depending on the type of parameter.
- Parameters
str (name) – A name to set on the parameter converter.
pos (callable that returns a
Parameterinstance) – The parameter factory for positional parameters.varargs (callable that returns a
Parameterinstance) – The parameter factory for*args-like parameters.named (callable that returns a
Parameterinstance) – The parameter factory for keyword parameters.varkwargs (callable that returns a
Parameterinstance) – The parameter factory for**kwargs-like parameters.kwargs (collections.abc.Mapping) – additional arguments to pass to the chosen factory.
- clize.parser.use_mixin(cls, *, kwargs={}, name=None)[source]¶
Like
use_class, but creates classes inheriting fromclsand one ofPositionalParameter,ExtraPosArgsParameter, andOptionParameter- Parameters
cls – The class to use as mixin.
kwargs (collections.abc.Mapping) – additional arguments to pass to the chosen factory.
name – The name to use for the converter. Uses
cls’s name if unset.
- class clize.parser.CliBoundArguments(sig, in_args, name, func=None, post_name=NOTHING, args=NOTHING, kwargs=NOTHING, meta=NOTHING)[source]¶
Command line arguments bound to a
CliSignatureinstance.- Parameters
sig (CliSignature) – The signature to bind against.
args (sequence) – The CLI arguments, minus the script name.
name (str) – The script name.
- sig¶
The signature being bound to.
- in_args¶
The CLI arguments, minus the script name.
- name¶
The script name.
- args = []¶
List of arguments to pass to the target function.
- kwargs = {}¶
Mapping of named arguments to pass to the target function.
- meta = {}¶
A dict for parameters to store data for the duration of the argument processing.
- post_name = []¶
List of words to append to the script name when passed to the target function.
The following attributes only exist while arguments are being processed:
- posparam = iter(sig.positional)¶
The iterator over the positional parameters used to process positional arguments.
- namedparam = dict(sig.aliases)¶
The
dictused to look up named parameters from their names.It is copied here so that the argument parsing process may add or remove parameters without affecting the original signature.
- unsatisfied = set(sig.required)¶
Required parameters that haven’t yet been satisfied.
- not_provided = set(sig.optional)¶
Optional parameters that haven’t yet received a value.
- skip = 0¶
Amount of arguments to skip.
Method generated by attrs for class CliBoundArguments.
- class clize.Parameter(display_name, undocumented=False, last_option=None)[source]¶
Bases:
objectRepresents a CLI parameter.
- Parameters
display_name (str) – The ‘default’ representation of the parameter.
undocumented (bool) – If true, hides the parameter from the command help.
last_option – If
True, the parameter will set theposarg_onlyflag on the bound arguments.
Also available as
clize.Parameter.
- class clize.parser.ParameterWithSourceEquivalent(argument_name, **kwargs)[source]¶
Bases:
clize.parser.ParameterParameter that relates to a function parameter in the source.
- Parameters
argument_name (str) – The name of the parameter.
- class clize.parser.HelperParameter(**kwargs)[source]¶
Bases:
clize.parser.ParameterParameter that doesn’t appear in CLI signatures but is used for instance as the
.stickyattribute of the bound arguments.
- class clize.parser.ParameterWithValue(conv=<function identity at 0x7febf37fdb80>, default=<unset>, cli_default=<unset>, **kwargs)[source]¶
Bases:
clize.parser.ParameterA parameter that takes a value from the arguments, with possible default and/or conversion.
- Parameters
conv (callable) – A callable to convert the value or raise
ValueError. Defaults toidentity.default – A default value for the parameter or
util.UNSET.
- clize.parser.value_converter(func=None, *, name=None, convert_default=None, convert_default_filter=<function <lambda> at 0x7febf37f7700>)[source]¶
Callables decorated with this can be used as a value converter.
- Parameters
name (str) –
Use this name to designate the parameter value type.
This should be in uppercase, with as few words as possible and no word delimiters.
The default is the name of the decorated function or type, modified to follow this rule.
convert_default (bool) –
If true, the value converter will be called with the default parameter value if none was supplied. Otherwise, the default parameter is used as-is.
Make sure to handle
Noneappropriately if you override this.Deprecated since version 5.0: Instruct users to use the
clize.Parameter.cli_defaultannotation instead to supply values that are converted by a CLI value converter.convert_convert_default_filter (function) –
If
convert_defaultis true, controls when the converter is called. The converter is used only if the given function returns true.Deprecated since version 5.0: Avoid
convert_defaultcompletely.
- class clize.parser.NamedParameter(aliases, **kwargs)[source]¶
Bases:
clize.parser.ParameterEquivalent of a keyword-only parameter in Python.
- Parameters
aliases (sequence of strings) – The arguments that trigger this parameter. The first alias is used to refer to the parameter. The first one is picked as
display_nameif unspecified.
- class clize.parser.FlagParameter(value, **kwargs)[source]¶
Bases:
clize.parser.OptionParameterA named parameter that takes no argument.
- Parameters
value – The value when the argument is present.
false_value – The value when the argument is given one of the false value triggers using
--param=xyz.
- class clize.parser.OptionParameter(aliases, **kwargs)[source]¶
Bases:
clize.parser.NamedParameter,clize.parser.ParameterWithValue,clize.parser.ParameterWithSourceEquivalentA named parameter that takes an argument.
- class clize.parser.IntOptionParameter(aliases, **kwargs)[source]¶
Bases:
clize.parser.OptionParameterA named parameter that takes an integer as argument. The short form of it can be chained with the short form of other named parameters.
- class clize.parser.PositionalParameter(conv=<function identity at 0x7febf37fdb80>, default=<unset>, cli_default=<unset>, **kwargs)[source]¶
Bases:
clize.parser.ParameterWithValue,clize.parser.ParameterWithSourceEquivalentEquivalent of a positional-only parameter in Python.
- class clize.parser.MultiParameter(min, max, **kwargs)[source]¶
Bases:
clize.parser.ParameterWithValueParameter that can collect multiple values.
- class clize.parser.ExtraPosArgsParameter(required=False, min=None, max=None, **kwargs)[source]¶
Bases:
clize.parser.MultiParameter,clize.parser.PositionalParameterParameter that forwards all remaining positional arguments to the callee.
Used to convert
*args-like parameters.
- class clize.parser.AppendArguments(**kwargs)[source]¶
Bases:
clize.parser.HelperParameter,clize.parser.MultiParameterHelper parameter that collects multiple values to be passed as positional arguments to the callee.
Similar to
ExtraPosArgsParameterbut does not correspond to a parameter in the source.
- class clize.parser.IgnoreAllArguments(**kwargs)[source]¶
Bases:
clize.parser.HelperParameter,clize.parser.ParameterHelper parameter for
FallbackCommandParameterthat ignores the remaining arguments.
- class clize.parser.FallbackCommandParameter(func, **kwargs)[source]¶
Bases:
clize.parser.NamedParameterParameter that sets an alternative function when triggered. When used as an argument other than the first all arguments are discarded.
- class clize.parser.AlternateCommandParameter(func, **kwargs)[source]¶
Bases:
clize.parser.FallbackCommandParameterParameter that sets an alternative function when triggered. Cannot be used as any argument but the first.
Exceptions¶
- class clize.UserError(message)¶
- class clize.errors.UserError(message)¶
An error to be displayed to the user.
If
clize.runcatches this error, the error will be printed without the associated traceback.def main(): raise clize.UserError("an error message") clize.run(main)
$ python usererror_example.py usererror_example.py: an error message
You can also specify other exception classes to be caught using
clize.run’scatchargument. However exceptions not based onUserErrorwill not have the command name displayed.
- class clize.ArgumentError(message)¶
- class clize.errors.ArgumentError(message)¶
An error related to argument parsing. If
clize.runcatches this error, the command’s usage line will be printed.def main(i:int): if i < 0: raise clize.ArgumentError("i must be positive") clize.run(main)
$ python argumenterror_example.py -- -5 argumenterror_example.py: i must be positive Usage: argumenterror_example.py i
Help generation¶
clize.help manages the generation of help messages obtained using --help.
HelpCli is the command-line interface for it. It is injected as an extra
alternate option by Clize. It can be replaced using Clize’s
helper_class parameter.
HelpForClizeDocstring constructs the help for clize’s docstring format.
It is invoked by HelpCli.get_help method. It can be swapped with the
builder parameter of HelpCli.
It uses sigtools.specifiers.signature to obtain which functions document the
parameters, elements_from_clize_docstring and helpstream_from_elements
process the docstring so it can be fed to
HelpForClizeDocstring.add_docstring.
- clize.help.LABEL_POS = 'Arguments'¶
The label for positional parameters
- clize.help.LABEL_OPT = 'Options'¶
The default label for named parameters
- clize.help.LABEL_ALT = 'Other actions'¶
The label for alternate actions like
--help
- class clize.help.HelpForParameters(header, footer, sections, after)[source]¶
Bases:
objectStores and displays help for a CLI with positional parameters, named parameters and/or alternate actions designated by a named parameter
Example output in relation to attribute names:
header section: param1 Param1 description After param2 param2 Param2 description footer
- header = []¶
A list of strings representing paragraphs in the help header/description.
A list of strings representing paragraphs in the help footer after everything else.
- sections = OrderedDict("section_name" => OrderedDict("param_name" => (param, "description")))¶
Maps section names to parameters and their help.
- after = {"param_name": ["paragraph"]}¶
Maps parameter names to additional paragraphs.
Method generated by attrs for class HelpForParameters.
- classmethod blank_from_signature(signature)[source]¶
Creates a blank instance with placeholders for the parameters in
signature.The parameters are sorted into three sections:
Positional parameters
Named parameters
Alternate options (e.g.
--help)
- show_usage(name)[source]¶
Returns a summary overview of the command’s parameters.
Option parameters are collapsed as
[OPTIONS]in the output.
- clize.help.elements_from_clize_docstring(source)[source]¶
Converts a string to an iterable of element tuples such as
(EL_FREE_TEXT, "text", False).The result is suitable for
helpstream_from_elements.See below for which tuples are produced/understood.
- clize.help.EL_LABEL = EL_LABEL¶
(EL_LABEL, "label")Indicates that the subsequent
EL_PARAM_DESCelements are under a section label.
- clize.help.EL_FREE_TEXT = EL_FREE_TEXT¶
(EL_FREE_TEXT, "paragraph", is_preformatted)Designates some free text. May be converted into header text, footer text, or additional paragraphs after a parameter depending on context.
The last free text elements at the end of a docstring are always considered to be the footer rather than additional paragraphs after a parameter.
is_preformattedis a boolean that indicates that the paragraph should not be reformatted.
- clize.help.EL_PARAM_DESC = EL_PARAM_DESC¶
(EL_PARAM_DESC, "param", "paragraph")Designates the description for a parameter.
- clize.help.EL_AFTER = EL_AFTER¶
(EL_AFTER, "param", "paragraph", is_preformatted)Explicitly designates an additional paragraph after a parameter. Unlike
EL_FREE_TEXT, this cannot be confused for a footer paragraph.
- clize.help.helpstream_from_elements(tokens)[source]¶
Transforms an iterable of non-explicit
EL_*elements to an iterable of explicitHELP_*elements.The result is suitable for
HelpForClizeDocstring.add_helpstream.
- clize.help.HELP_HEADER = HELP_HEADER¶
(HELP_HEADER, "paragraph", is_preformatted)Designates a paragraph that appears before the parameter descriptions.
- clize.help.HELP_FOOTER = HELP_FOOTER¶
(HELP_FOOTER, "paragraph", is_preformatted)Designates a paragraph that appears after the parameter descriptions.
- clize.help.HELP_PARAM_DESC = HELP_PARAM_DESC¶
(HELP_PARAM_DESC, "param", "label", "paragraph")Designates a parameter description. If no label was specified
Noneshould take its place.
- clize.help.HELP_PARAM_AFTER = HELP_PARAM_AFTER¶
(HELP_PARAM_AFTER, "param", "paragraph", is_preformatted)Designates a paragraph after a parameter description.
- class clize.help.HelpForAutodetectedDocstring(*args, **kwargs)[source]¶
Bases:
clize.help.HelpForParametersBuilds generic parameter help from the docstrings of Clize instances
Uses a custom docstring format. See clize docstring.
Method generated by attrs for class HelpForParameters.
- classmethod from_subject(subject, owner)[source]¶
Constructs a
HelpForClizeDocstringinstance and populates it with data from aClizeinstance.It uses the parameters’
parser.Parameter.prepare_helpand reads the docstrings of functions from which the parameters originate.
- add_from_parameters(parameters)[source]¶
Uses
parser.Parameter.prepare_helpon an iterable of parameters
- add_from_parameter_sources(subject)[source]¶
Processes the docstrings of the functions that have parameters in
subjectand adds their information to this instance.- Parameters
subject (Clize) – the Clize runner to document
- add_docstring(docstring, name, pnames, primary)[source]¶
Parses and integrates info from a docstring to this instance.
- Parameters
docstring (str) – The docstring to be read. Must be de-indented using something like
inspect.cleandoc.pnames (set) – If not
None, only add info about these parameter names.primary (bool) – Add headers and footers from this docstring.
- parse_docstring(docstring)[source]¶
Alias of
add_docstringfor backwards compatibility.
- add_helpstream(stream, pnames, primary)[source]¶
Add an iterable of tuples starting with
HELP_to this instance.- Parameters
stream (iterable) – An iterable of
(HELP_*, ...)tuples, as produced byhelpstream_from_elementspnames (set) – If not
None, only add info about these parameter names.primary (bool) – Add headers and footers from this docstring.
- class clize.help.HelpForClizeDocstring(*args, **kwargs)[source]¶
Bases:
clize.help.HelpForAutodetectedDocstringMethod generated by attrs for class HelpForParameters.
- class clize.help.HelpForSphinxDocstring(*args, **kwargs)[source]¶
Bases:
clize.help.HelpForClizeDocstringBuilds generic parameter help from the docstrings of Clize instances
Understands docstrings written for Sphinx’s
autodoc.Method generated by attrs for class HelpForParameters.
- class clize.help.HelpForSubcommands(usages, subcommands, header, footer)[source]¶
Bases:
objectStores help for subcommand dispatchers.
- subcommands¶
An ordered mapping of the subcommand names to their description.
- header¶
Iterable of paragraphs for the help header.
Iterable of paragraphs for the help footnotes.
Method generated by attrs for class HelpForSubcommands.
- classmethod from_subject(subject, owner)[source]¶
Constructs a
HelpForSubcommandsinstance and populates it with data from aClizeinstance.It uses the parameters’
parser.Parameter.prepare_helpand reads the docstrings of functions from which the parameters originate.- Parameters
owner (SubcommandDispatcher) – The subcommand dispatcher being documented.
- class clize.help.HelpCli(subject, owner, builder=<bound method HelpForAutodetectedDocstring.from_subject of <class 'clize.help.HelpForAutodetectedDocstring'>>)[source]¶
Bases:
objectA command-line interface for constructing and accessing the help and other meta-information about a CLI
- cli(name: clize.parameters.pass_name, usage=False, *args: clize.Parameter.UNDOCUMENTED)[source]¶
Show the help
usage: Only show the full usage
- property description¶
A short description of this command
- clize.help.ClizeHelp¶
alias of
clize.help.HelpCli
Compatibility with older clize releases¶
- clize.clize(fn=None, *, alias={}, force_positional=(), coerce={}, require_excess=False, extra=(), use_kwoargs=None)[source]¶
Compatibility with clize<3.0 releases. Decorates a function in order to be passed to
clize.run. See Upgrading from clize 1 and 2.
- clize.make_flag(source, names, default=False, type=None, help='', takes_argument=0)[source]¶
Compatibility with clize<3.0 releases. Creates a parameter instance. See Upgrading from clize 1 and 2.