API
- class cyclopts.App(name=None, help=None, usage=None, *, default_command=None, default_parameter=None, config=None, version=<function _default_version>, version_flags=['--version'], show=True, console=None, help_flags=['--help', '-h'], help_format=None, version_format=None, group=None, group_arguments=None, group_parameters=None, group_commands=None, converter=None, validator=None, name_transform=None)[source]
Cyclopts Application.
- name: str | Iterable[str] | None = None
Name of application, or subcommand if registering to another application. Name fallback resolution:
User specified
name.If a
defaultfunction has been registered, the name of that function.If the module name is
__main__.py, the name of the encompassing package.The value of
sys.argv[0].
Multiple names can be provided in the case of a subcommand, but this is relatively unusual.
- help_flags: str | Iterable[str] = ("--help", "-h")
Tokens that trigger
help_print(). Set to an empty list to disable help feature. Defaults to["--help", "-h"]. Cannot be changed after instantiating the app.
- help_format: Literal['plaintext', 'markdown', 'md', 'restructuredtext', 'rst'] | None = None
The markup language of docstring function descriptions. If
None, fallback to parentinghelp_format. If nohelp_formatis defined, falls back to"restructuredtext".
- version_format: Literal['plaintext', 'markdown', 'md', 'restructuredtext', 'rst'] | None = None
The markup language of the version string; used in
version_print(). IfNone, fallback to parentingversion_format. If noversion_formatis defined, falls back to resolvedhelp_format.
- usage: str | None = None
Text to be displayed in lieue of the default
Usage: app COMMAND ...at the beginning of the help-page. Set to an empty-string""to disable showing the default usage.
- version: None | str | Callable = None
Version to be displayed when a token of
version_flagsis parsed. Defaults to attempting to using version of the package instantiatingApp. If aCallable, it will be invoked with no arguments when version is queried.
- version_flags: str | Iterable[str] = ("--version",)
Token(s) that trigger
version_print(). Set to an empty list to disable version feature. Defaults to["--version"]. Cannot be changed after instantiating the app.
- console: rich.console.Console = None
Default
rich.console.Consoleto use when displaying runtime errors. Cyclopts console resolution is as follows:Any explicitly passed in console to methods like
App.__call__(),App.parse_args(), etc.The relevant subcommand's
App.consoleattribute, if notNone.The parenting
App.console(and so on), if notNone.
- default_parameter: Parameter = None
Default
Parameterconfiguration. Unspecified values of command-annotatedParameterwill inherit these values. See Parameter Resolution Order for more details.
- group: None | str | Group | Iterable[str | Group] = None
The group(s) that
default_commandbelongs to.
- group_arguments: Group = Group("Arguments")
The default group that positional-only parameters are assigned to.
- group_parameters: Group = Group("Parameters")
The default group that non-positional-only parameters are assigned to.
- converter: Callable | None = None
A function where all the converted CLI-provided variables will be keyword-unpacked, regardless of their positional/keyword-type in the command function signature. The python variable names will be used, which may differ from their CLI names.
def converter(**kwargs) -> Dict[str, Any]: "Return an updated dictionary."
The returned dictionary will be used passed along to the command invocation. This converter runs after
ParameterandGroupconverters.
- validator: None | Callable | List[Callable] = []
A function where all the converted CLI-provided variables will be keyword-unpacked, regardless of their positional/keyword-type in the command function signature. The python variable names will be used, which may differ from their CLI names.
Example usage:
def validator(**kwargs): "Raise an exception if something is invalid."
This validator runs after
ParameterandGroupvalidators.The raised error message will be presented to the user with python-variables prepended with "--" remapped to their CLI counterparts.
- name_transform: Callable[[str], str] | None = None
A function that converts function names to their CLI command counterparts.
The function must have signature:
def name_transform(s: str) -> str: ...
If
None(default value), usescyclopts.default_name_transform(). If a subapp, inherits from first non-Noneparent.
- config: None | Callable | Iterable[Callable] = None
A function or list of functions that are consecutively applied to keyword arguments. These function(s) are called before any additional conversion and validation. Each function must have signature:
def config(apps: Tuple[App, ...], commands: Tuple[str, ...], mapping: Dict[str, Union[Unset, List[str]]]): """Modifies given mapping inplace with some injected values. Parameters ---------- apps: Tuple[App, ...] The application hierarchy that led to the current command function. The current command app is the last element of this tuple. commands: Tuple[str, ...] The CLI strings that led to the current command function. mapping: Dict[str, Union[Unset, List[str]]] A dictionary mapping CLI keyword names to their tokens (before App and Group converters/validators have been invoked). For example, if the user specifies --my-var=foo, then this dictionary will be {"my-var": ["foo"]}. If the value is an cyclopts.config.Unset object, then no tokens have been parsed for that parameter yet. Deleting keys from this dictionary will unset their value. """
The intended use-case of this feature is to allow users to specify functions that can load defaults from some external configuration. See cyclopts.config for useful builtins.
- version_print(console=None)[source]
Print the application version.
- Return type:
- Parameters:
console (rich.console.Console) -- Console to print version string to. If not provided, follows the resolution order defined in
App.console.
- __getitem__(key)[source]
Get the subapp from a command string.
All commands get registered to Cyclopts as subapps. The actual function handler is at
app[key].default_command.- Return type:
- parse_commands(tokens=None)[source]
Extract out the command tokens from a command.
- Return type:
- Parameters:
tokens (Union[None, str, Iterable[str]]) -- Either a string, or a list of strings to launch a command. Defaults to
sys.argv[1:]- Returns:
List[str] -- Tokens that are interpreted as a valid command chain.
List[App] -- The associated
Appobject with each of those tokens.List[str] -- The remaining non-command tokens.
- command(obj=None, name=None, **kwargs)[source]
Decorator to register a function as a CLI command.
- Return type:
Union[TypeVar(T, bound=Callable),Callable[[TypeVar(T, bound=Callable)],TypeVar(T, bound=Callable)]]- Parameters:
obj (Optional[Callable]) -- Function or
Appto be registered as a command.name (Union[None, str, Iterable[str]]) --
Name(s) to register the
objto. If not provided, defaults to:If registering an
App, then the app's name.If registering a function, then the function's name.
**kwargs -- Any argument that
Appcan take.
- default(obj=None, *, converter=None, validator=None)[source]
Decorator to register a function as the default action handler.
- parse_known_args(tokens=None, *, console=None)[source]
Interpret arguments into a function,
BoundArguments, and any remaining unknown tokens.- Return type:
- Parameters:
tokens (Union[None, str, Iterable[str]]) -- Either a string, or a list of strings to launch a command. Defaults to
sys.argv[1:]console (rich.console.Console) -- Console to print help and runtime Cyclopts errors. If not provided, follows the resolution order defined in
App.console.
- Returns:
command (Callable) -- Bare function to execute.
bound (inspect.BoundArguments) -- Bound arguments for
command.unused_tokens (List[str]) -- Any remaining CLI tokens that didn't get parsed for
command.
- parse_args(tokens=None, *, console=None, print_error=True, exit_on_error=True, verbose=False)[source]
Interpret arguments into a function and
BoundArguments.- Return type:
- Raises:
UnusedCliTokensError -- If any tokens remain after parsing.
- Parameters:
tokens (Union[None, str, Iterable[str]]) -- Either a string, or a list of strings to launch a command. Defaults to
sys.argv[1:].console (rich.console.Console) -- Console to print help and runtime Cyclopts errors. If not provided, follows the resolution order defined in
App.console.print_error (bool) -- Print a rich-formatted error on error. Defaults to
True.exit_on_error (bool) -- If there is an error parsing the CLI tokens invoke
sys.exit(1). Otherwise, continue to raise the exception. Defaults toTrue.verbose (bool) -- Populate exception strings with more information intended for developers. Defaults to
False.
- Returns:
command (Callable) -- Function associated with command action.
bound (inspect.BoundArguments) -- Parsed and converted
argsandkwargsto be used when callingcommand.
- __call__(tokens=None, *, console=None, print_error=True, exit_on_error=True, verbose=False)[source]
Interprets and executes a command.
- Parameters:
tokens (Union[None, str, Iterable[str]]) -- Either a string, or a list of strings to launch a command. Defaults to
sys.argv[1:].console (rich.console.Console) -- Console to print help and runtime Cyclopts errors. If not provided, follows the resolution order defined in
App.console.print_error (bool) -- Print a rich-formatted error on error. Defaults to
True.exit_on_error (bool) -- If there is an error parsing the CLI tokens invoke
sys.exit(1). Otherwise, continue to raise the exception. Defaults toTrue.verbose (bool) -- Populate exception strings with more information intended for developers. Defaults to
False.
- Returns:
return_value -- The value the parsed command handler returns.
- Return type:
Any
- help_print(tokens=None, *, console=None)[source]
Print the help page.
- Return type:
- Parameters:
tokens (Union[None, str, Iterable[str]]) -- Tokens to interpret for traversing the application command structure. If not provided, defaults to
sys.argv.console (rich.console.Console) -- Console to print help and runtime Cyclopts errors. If not provided, follows the resolution order defined in
App.console.
- interactive_shell(prompt='$ ', quit=None, dispatcher=None, **kwargs)[source]
Create a blocking, interactive shell.
All registered commands can be executed in the shell.
- Return type:
- Parameters:
prompt (str) -- Shell prompt. Defaults to
"$ ".quit (Union[str, Iterable[str]]) -- String or list of strings that will cause the shell to exit and this method to return. Defaults to
["q", "quit"].dispatcher (Optional[Dispatcher]) --
Optional function that subsequently invokes the command. The
dispatcherfunction must have signature:def dispatcher(command: Callable, bound: inspect.BoundArguments) -> Any: return command(*bound.args, **bound.kwargs)
The above is the default dispatcher implementation.
**kwargs -- Get passed along to
parse_args().
- class cyclopts.Parameter(name=None, converter=None, validator=(), negative=None, group=None, parse=None, show=None, show_default=None, show_choices=None, help=None, show_env_var=None, env_var=None, env_var_split=<function env_var_split>, negative_bool=None, negative_iterable=None, required=None, allow_leading_hyphen=False, *, name_transform=None)[source]
Cyclopts configuration for individual function parameters.
Cyclopts configuration for individual function parameters.
- name: None | str | Iterable[str] = None
Name(s) to expose to the CLI. Defaults to the python parameter's name, prepended with
--. Single-character options should start with-. Full-name options should start with--.
- converter: Callable | None = None
A function that converts string token(s) into an object. The converter must have signature:
def converter(type_, *args) -> Any: pass
If not provided, defaults to Cyclopts's internal coercion engine.
- validator: None | Callable | Iterable[Callable] = None
A function (or list of functions) that validates data returned by the
converter.def validator(type_, value: Any) -> None: pass # Raise a TypeError, ValueError, or AssertionError here if data is invalid.
- group: None | str | Group | Iterable[str | Group] = None
The group(s) that this parameter belongs to. This can be used to better organize the help-page, and/or to add additional conversion/validation logic (such as ensuring mutually-exclusive arguments).
If
None, defaults to one of the following groups:Parenting
App.group_argumentsif the parameter isPOSITIONAL_ONLY. By default, this isGroup("Arguments").Parenting
App.group_parametersotherwise. By default, this isGroup("Parameters").
- negative: None | str | Iterable[str] = None
Name(s) for empty iterables or false boolean flags. For booleans, defaults to
--no-{name}. For iterables, defaults to--empty-{name}. Set to an empty list to disable this feature.
- negative_bool: str | None = None
Prefix for negative boolean flags. Must start with
"--". Defaults to"--no-".
- negative_iterable: str | None = None
Prefix for empty iterables (like lists and sets) flags. Must start with
"--". Defaults to"--empty-".
- allow_leading_hyphen: bool = False
Allow parsing non-numeric values that begin with a hyphen
-. This is disabled by default, allowing for more helpful error messages for unknown CLI options.
- parse: bool | None = True
Attempt to use this parameter while parsing. Annotated parameter must be keyword-only.
- required: bool | None = None
Indicates that the parameter must be supplied on the help-page. Does not directly enforce whether or not a parameter must be supplied; only influences the help-page. Defaults to inferring from the function signature; i.e.
Falseif the parameter has a default,Trueotherwise.
- show: bool | None = None
Show this parameter on the help screen. If
False, state of all othershow_*flags are ignored. Defaults toparsevalue (True).
- show_default: bool | None = None
If a variable has a default, display the default on the help page. Defaults to
None, similar toTrue, but will not display the default if it'sNone.
- show_choices: bool | None = True
If a variable has a set of choices, display the choices on the help page. Defaults to
True.
- help: str | None = None
Help string to be displayed on the help page. If not specified, defaults to the docstring.
- show_env_var: bool | None = True
If a variable has
env_varset, display the variable name on the help page. Defaults toTrue.
- env_var: None | str | Iterable[str] = None
Fallback to environment variable(s) if CLI value not provided. If multiple environment variables are given, the left-most environment variable with a set value will be used. If no environment variable is set, Cyclopts will fallback to the function-signature default.
- env_var_split: Callable = cyclopts.env_var_split
Function that splits up the read-in
env_varvalue. The function must have signature:def env_var_split(type_: type, val: str) -> List[str]: ...
where
type_is the associated parameter type-hint, andvalis the environment value.
- name_transform: Callable[[str], str] | None = None
A function that converts python parameter names to their CLI command counterparts.
The function must have signature:
def name_transform(s: str) -> str: ...
If
None(default value), usescyclopts.default_name_transform().
- class cyclopts.Group(name='', help='', sort_key=None, *, show=None, converter=None, validator=None, default_parameter=None)[source]
A group of parameters and/or commands in a CLI application.
- name: str = ""
Group name used for the help-page and for group-referenced-by-string. This is a title, so the first character should be capitalized. If a name is not specified, it will not be shown on the help-page.
- help: str = ""
Additional documentation shown on the help-page. This will be displayed inside the group's panel, above the parameters/commands.
- show: bool | None = None
Show this group on the help-page. Defaults to
None, which will only show the group if anameis provided.
- sort_key: Any = None
Modifies group-panel display order on the help-page.
If
sort_key, or any of it's contents, areCallable, then invoke itsort_key(group)and apply the returned value to (2) ifNone, (3) otherwise.For all groups with
sort_key==None(default value), sort them alphabetically. These sorted groups will be displayed aftersort_key != Nonelist (see 3).For all groups with
sort_key!=None, sort them by(sort_key, group.name). It is the user's responsibility thatsort_keys are comparable.
Example usage:
@app.command(group=Group("4", sort_key=5)) def cmd1(): pass @app.command(group=Group("3", sort_key=lambda x: 10)) def cmd2(): pass @app.command(group=Group("2", sort_key=lambda x: None)) def cmd3(): pass @app.command(group=Group("1")) def cmd4(): pass
Resulting help-page:
Usage: app COMMAND App Help String Line 1. ╭─ 4 ────────────────────────────────────────────────────────────────╮ │ cmd1 │ ╰────────────────────────────────────────────────────────────────────╯ ╭─ 3 ────────────────────────────────────────────────────────────────╮ │ cmd2 │ ╰────────────────────────────────────────────────────────────────────╯ ╭─ 1 ────────────────────────────────────────────────────────────────╮ │ cmd4 │ ╰────────────────────────────────────────────────────────────────────╯ ╭─ 2 ────────────────────────────────────────────────────────────────╮ │ cmd3 │ ╰────────────────────────────────────────────────────────────────────╯ ╭─ Commands ─────────────────────────────────────────────────────────╮ │ --help,-h Display this message and exit. │ │ --version Display application version. │ ╰────────────────────────────────────────────────────────────────────╯
- default_parameter: Parameter | None = None
Default
Parameterin the parameter-resolution-stack that goes betweenApp.default_parameterand the function signature'sAnnotatedParameter. The providedParameteris not allowed to have agroupvalue.
- converter: Callable | None
A function where the CLI-provided group variables will be keyword-unpacked, regardless of their positional/keyword-type in the command function signature. The python variable names will be used, which may differ from their CLI names.
def converter(**kwargs) -> Dict[str, Any]: """Return an updated dictionary."""
The python variable names will be used, which may differ from their CLI names. If a variable isn't populated from the CLI or environment variable, it will not be provided to the converter. I.e. defaults from the function signature are not applied prior.
The returned dictionary will be used for subsequent execution. Removing variables from the returned dictionary will unbind them. When used with
@app.command, all function arguments are provided.
- validator: Callable | None = None
A function (or list of functions) where the CLI-provided group variables will be keyword-unpacked, regardless of their positional/keyword-type in the command function signature. The python variable names will be used, which may differ from their CLI names.
Example usage:
def validator(**kwargs): "Raise an exception if something is invalid."
Validators are not invoked on command groups. The group-validator runs after the group-converter.
The raised error message will be presented to the user with python-variables prepended with
"--"remapped to their CLI counterparts.In the following example, the python variable name
"--bar"in the error message is remapped to"--buzz".from cyclopts import Parameter, App, Group from typing import Annotated app = App() def upper_case_only(**kwargs): for k, v in kwargs.items(): if not v.isupper(): raise ValueError(f'--{k} value "{v}" needs to be uppercase.') group = Group("", validator=upper_case_only) @app.default def foo( bar: Annotated[str, Parameter(name="--fizz", group=group)], baz: Annotated[str, Parameter(name="--buzz", group=group)], ): pass app()
$ python meow.py ALICE bob ╭─ Error ─────────────────────────────────────────────────╮ │ --buzz value "bob" needs to be uppercase. │ ╰─────────────────────────────────────────────────────────╯
- classmethod create_ordered(*args, sort_key=None, **kwargs)[source]
Create a group with a globally incremented
sort_key.Used to create a group that will be displayed after a previously declared
Group.create_ordered()group on the help-page.If a
sort_keyis provided, it is prepended to the globally incremented counter value (i.e. has priority during sorting).
- cyclopts.convert(type_, *args, converter=None, name_transform=None)[source]
Coerce variables into a specified type.
Internally used to coercing string CLI tokens into python builtin types. Externally, may be useful in a custom converter. See Cyclopt's automatic coercion rules Coercion Rules.
If
type_is not iterable, then each element of*argswill be converted independently. If there is more than one element, then the return type will be aTuple[type_, ...]. If there is a single element, then the return type will betype_.If
type_is iterable, then all elements of*argswill be collated.- Parameters:
type (Type) -- A type hint/annotation to coerce
*argsinto.*args (str) -- String tokens to coerce.
converter (Optional[Callable[[Type, str], Any]]) --
An optional function to convert tokens to the inner-most types. The converter should have signature:
def converter(type_: type, value: str) -> Any: "Perform conversion of string token."
This allows to use the
convert()function to handle the the difficult task of traversing lists/tuples/unions/etc, while leaving the final conversion logic to the caller.name_transform (Optional[Callable[[str], str]]) --
Currently only used for
Enumtype hints. A function that transforms enum names and CLI values into a normalized format.The function should have signature:
def name_transform(s: str) -> str: "Perform name transform."
where the returned value is the name to be used on the CLI.
If
None, defaults tocyclopts.default_name_transform.
- Returns:
Coerced version of input
*args.- Return type:
Any
- cyclopts.default_name_transform(s)[source]
Converts a python identifier into a CLI token.
Performs the following operations (in order):
Convert the string to all lowercase.
Replace
_with-.Strip any leading/trailing
-(also stripping_, due to point 2).
Intended to be used with
App.name_transformandParameter.name_transform.
- cyclopts.env_var_split(type_, val, *, delimiter=None)[source]
Type-dependent environment variable value splitting.
Performs splitting when:
The
type_is some variant ofIterable[pathlib.Path]objects. If Windows, split on;, otherwise split on:.Otherwise, if the
type_is anIterable, split on whitespace. Leading/trailing whitespace of each output element will be stripped.
Is the default value for
cyclopts.App.env_var_split.
Validators
Cyclopts has several builtin validators for common CLI inputs.
- class cyclopts.validators.LimitedChoice(min=0, max=None)[source]
Group validator that limits the number of selections per group.
Commonly used for enforcing mutually-exclusive parameters (default behavior).
- class cyclopts.validators.Number(*, lt=None, lte=None, gt=None, gte=None)[source]
Limit input number to a value range.
- class cyclopts.validators.Path(*, exists=False, file_okay=True, dir_okay=True)[source]
Assertions on properties of
pathlib.Path.
Types
Cyclopts has builtin pre-defined annotated-types for common validation configurations. All definitions in this section are just predefined annotations for convenience:
Annotated[..., Parameter(...)]
Due to Cyclopts's advanced Parameter resolution engine, these annotations can themselves be annotated. E.g:
Annotated[PositiveInt, Parameter(...)]
Path
Path annotated types for checking existence, type, and performing path-resolution.
- cyclopts.types.ResolvedPath
A
Pathfile or directory.resolve()is invoked prior to returning the path.
- cyclopts.types.ResolvedExistingPath
A
Pathfile or directory that must exist.resolve()is invoked prior to returning the path.
- cyclopts.types.ResolvedDirectory
A
Pathdirectory.resolve()is invoked prior to returning the path.
- cyclopts.types.ResolvedExistingDirectory
A
Pathdirectory that must exist.resolve()is invoked prior to returning the path.
Number
Annotated types for checking common int/float value constraints.
Config
Cyclopts has builtin configuration classes to be used with App.config for loading user-defined defaults in many common scenarios.
All Cyclopts builtins index into the configuration file with the following rules:
Apply
root_keys(if provided) to enter the project's configuration namespace.Apply the command name(s) to enter the current command's configuration namespace.
Apply each key/value pair if CLI arguments have not been provided for that parameter.
- class cyclopts.config.Toml(path, root_keys=(), *, must_exist=False, search_parents=False, allow_unknown=False)[source]
Automatically read configuration from Toml file.
- root_keys: Iterable[str] = None
Keys that lead to your application's configuration. For example, if referencing a
pyproject.toml, it is common to store all of your projects configuration under:[tool.myproject]So, your Cyclopts
Appshould be configured as:app = cyclopts.App(config=cyclopts.config.Toml("pyproject.toml", root_keys=("tool", "myproject")))
- must_exist: bool = False
The configuration file must exist. If a matching file is not found, raises
FileNotFoundError.
- class cyclopts.config.Yaml(path, root_keys=(), *, must_exist=False, search_parents=False, allow_unknown=False)[source]
Automatically read configuration from Yaml file.
- root_keys: Iterable[str] = None
Keys that lead to your application's configuration in the YAML file.
- must_exist: bool = False
The configuration file must exist. If a matching file is not found, raises
FileNotFoundError.
- class cyclopts.config.Json(path, root_keys=(), *, must_exist=False, search_parents=False, allow_unknown=False)[source]
Automatically read configuration from Json file.
- root_keys: Iterable[str] = None
Keys that lead to your application's configuration in the YAML file.
- must_exist: bool = False
The configuration file must exist. If a matching file is not found, raises
FileNotFoundError.
- class cyclopts.config.Env(prefix='', *, command=True, split=<function env_var_split>)[source]
Automatically derive environment variable names to read configurations from.
For example, consider the following app:
import cyclopts app = cyclopts.App(config=cyclopts.config.Env("MY_SCRIPT_")) @app.command def my_command(foo, bar): print(f"{foo=} {bar=}") app()
If values for
fooandbarare not supplied by the command line, the app will check the environment variablesMY_SCRIPT_MY_COMMAND_FOOandMY_SCRIPT_MY_COMMAND_BAR, respectively:$ python my_script.py my-command 1 2 foo=1 bar=2 $ export MY_SCRIPT_MY_COMMAND_FOO=100 $ python my_script.py my-command --bar=2 foo=100 bar=2 $ python my_script.py my-command 1 2 foo=1 bar=2
- class cyclopts.config.Unset(iparam, related=_Nothing.NOTHING)[source]
Placeholder object for a parameter that does not yet have any associated string tokens.
Used with
App.config.- Parameters:
iparam (inspect.Parameter) -- The corresponding
inspect.Parameterfor the unset variable.related (set[str]) -- Other CLI names that map to the same
inspect.Parameter. These may be aliases, or things like negative flags.
Other CLI keys that map to the same
inspect.Parameterthat have parsed token(s).
Exceptions
- exception cyclopts.CycloptsError(*, msg=None, verbose=True, root_input_tokens=None, unused_tokens=None, target=None, cli2parameter=None, parameter2cli=None, command_chain=None, app=None, console=None)[source]
Bases:
ExceptionRoot exception for runtime errors.
As CycloptsErrors bubble up the Cyclopts stack, more information is added to it. Finally,
cyclopts.exceptions.format_cyclopts_error()formats the message nicely for the user.-
verbose:
bool More verbose error messages; aimed towards developers debugging their Cyclopts app. Defaults to
False.
-
cli2parameter:
Optional[Dict[str,Tuple[Parameter,Any]]] Dictionary mapping CLI strings to python parameters.
-
verbose:
- exception cyclopts.ValidationError(*, msg=None, verbose=True, root_input_tokens=None, unused_tokens=None, target=None, cli2parameter=None, parameter2cli=None, command_chain=None, app=None, console=None, value, parameter=None, group=None)[source]
Bases:
CycloptsErrorValidator function raised an exception.
- exception cyclopts.UnknownOptionError(*, msg=None, verbose=True, root_input_tokens=None, unused_tokens=None, target=None, cli2parameter=None, parameter2cli=None, command_chain=None, app=None, console=None, token)[source]
Bases:
CycloptsErrorUnknown/unregistered option provided by the cli.
- exception cyclopts.CoercionError(*, msg=None, verbose=True, root_input_tokens=None, unused_tokens=None, target=None, cli2parameter=None, parameter2cli=None, command_chain=None, app=None, console=None, input_value='', target_type=None, parameter=None)[source]
Bases:
CycloptsErrorThere was an error performing automatic type coercion.
- exception cyclopts.InvalidCommandError(*, msg=None, verbose=True, root_input_tokens=None, unused_tokens=None, target=None, cli2parameter=None, parameter2cli=None, command_chain=None, app=None, console=None)[source]
Bases:
CycloptsErrorCLI token combination did not yield a valid command.
- msg: Optional[str]
If set, override automatic message generation.
- verbose: bool
More verbose error messages; aimed towards developers debugging their Cyclopts app. Defaults to
False.
- unused_tokens: Optional[List[str]]
Leftover tokens after parsing is complete.
- target: Optional[Callable]
The python function associated with the command being parsed.
- cli2parameter: Optional[Dict[str, Tuple[inspect.Parameter, Any]]]
Dictionary mapping CLI strings to python parameters.
- parameter2cli: Optional[ParameterDict]
Dictionary mapping function parameters to possible CLI tokens.
- command_chain: Optional[Iterable[str]]
List of command that lead to
target.
- app: Optional['App']
The Cyclopts application itself.
- console: Optional['Console']
Rich console to display runtime errors.
- exception cyclopts.UnusedCliTokensError(*, msg=None, verbose=True, root_input_tokens=None, unused_tokens=None, target=None, cli2parameter=None, parameter2cli=None, command_chain=None, app=None, console=None)[source]
Bases:
CycloptsErrorNot all CLI tokens were used as expected.
- exception cyclopts.MissingArgumentError(*, msg=None, verbose=True, root_input_tokens=None, unused_tokens=None, target=None, cli2parameter=None, parameter2cli=None, command_chain=None, app=None, console=None, parameter, tokens_so_far=_Nothing.NOTHING)[source]
Bases:
CycloptsErrorA parameter had insufficient tokens to be populated.