API
- class cyclopts.App(name=None, help=None, usage=None, *, default_command=None, default_parameter=None, version=_Nothing.NOTHING, version_flags=['--version'], show=True, console=None, help_flags=['--help', '-h'], help_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
default
function 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_format
is defined, falls back to"restructuredtext"
.
- 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_flags
is 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.Console
to 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.console
attribute, if notNone
.The parenting
App.console
(and so on), if notNone
.
- group: None | str | Group | Iterable[str | Group] = None
The group(s) that
default_command
belongs 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
Parameter
andGroup
converters.
- 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
Parameter
andGroup
validators.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-None
parent.
- __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.
- 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
App
object 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:
- Parameters:
obj (Optional[Callable]) -- Function or
App
to be registered as a command.name (Union[None, str, Iterable[str]]) --
Name(s) to register the
obj
to. 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
App
can 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:]
- 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
args
andkwargs
to 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
dispatcher
function 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, 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_arguments
if the parameter isPOSITIONAL_ONLY
. By default, this isGroup("Arguments")
.Parenting
App.group_parameters
otherwise. 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.
False
if the parameter has a default,True
otherwise.
- show: bool | None = None
Show this parameter on the help screen. If
False
, state of all othershow_*
flags are ignored. Defaults toparse
value (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_var
set, 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.
- 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 aname
is 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 != None
list (see 3).For all groups with
sort_key!=None
, sort them by(sort_key, group.name)
. It is the user's responsibility thatsort_key
s 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
Parameter
in the parameter-resolution-stack that goes betweenApp.default_parameter
and the function signature'sAnnotated
Parameter
. The providedParameter
is not allowed to have agroup
value.
- 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_key
is 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*args
will 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*args
will be collated.- Parameters:
type (Type) -- A type hint/annotation to coerce
*args
into.*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: ...
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
Enum
type 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: ...
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): :rtype:
str
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_transform
andParameter.name_transform
.
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
Path
file or directory.resolve()
is invoked prior to returning the path.
- cyclopts.types.ResolvedExistingPath
A
Path
file or directory that must exist.resolve()
is invoked prior to returning the path.
- cyclopts.types.ResolvedDirectory
A
Path
directory.resolve()
is invoked prior to returning the path.
- cyclopts.types.ResolvedExistingDirectory
A
Path
directory that must exist.resolve()
is invoked prior to returning the path.
Number
Annotated types for checking common int/float value constraints.
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:
Exception
Root 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:
CycloptsError
Validator 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:
CycloptsError
Unknown/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:
CycloptsError
There 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:
CycloptsError
CLI 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[List[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:
CycloptsError
Not 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)[source]
Bases:
CycloptsError
A parameter had insufficient tokens to be populated.