miio.click_common module
Click commons.
This file contains common functions for cli tools.
- class miio.click_common.DeviceGroup(device_class, name=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, result_callback_pass_device=True, **attrs)[source]
Bases:
MultiCommand
- class Command(name, decorators, *, default_output=None, **kwargs)[source]
Bases:
object
- property command_name
- context_class
alias of
Context
- collect_usage_pieces(ctx: Context) List[str]
Returns all the pieces that go into the usage line and returns it as a list of strings.
- format_commands(ctx: Context, formatter: HelpFormatter) None
Extra format methods for multi methods that adds all the commands after the options.
- format_epilog(ctx: Context, formatter: HelpFormatter) None
Writes the epilog into the formatter if it exists.
- format_help(ctx: Context, formatter: HelpFormatter) None
Writes the help into the formatter if it exists.
This is a low-level method called by
get_help()
.This calls the following methods:
- format_help_text(ctx: Context, formatter: HelpFormatter) None
Writes the help text to the formatter if it exists.
- format_options(ctx: Context, formatter: HelpFormatter) None
Writes all the options into the formatter if they exist.
- format_usage(ctx: Context, formatter: HelpFormatter) None
Writes the usage line into the formatter.
This is a low-level method called by
get_usage()
.
- get_command(ctx, cmd_name)[source]
Given a context and a command name, this returns a
Command
object if it exists or returns None.
- get_help(ctx: Context) str
Formats the help into a string and returns it.
Calls
format_help()
internally.
- get_short_help_str(limit: int = 45) str
Gets short help for the command or makes it by shortening the long help string.
- get_usage(ctx: Context) str
Formats the usage line into a string and returns it.
Calls
format_usage()
internally.
- invoke(ctx: Context) Any
Given a context, this invokes the attached callback (if it exists) in the right way.
- main(args: Sequence[str] | None = None, prog_name: str | None = None, complete_var: str | None = None, standalone_mode: bool = True, windows_expand_args: bool = True, **extra: Any) Any
This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted,
SystemExit
needs to be caught.This method is also available by directly calling the instance of a
Command
.- Parameters:
args – the arguments that should be used for parsing. If not provided,
sys.argv[1:]
is used.prog_name – the program name that should be used. By default the program name is constructed by taking the file name from
sys.argv[0]
.complete_var – the environment variable that controls the bash completion support. The default is
"_<prog_name>_COMPLETE"
with prog_name in uppercase.standalone_mode – the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to False they will be propagated to the caller and the return value of this function is the return value of
invoke()
.windows_expand_args – Expand glob patterns, user dir, and env vars in command line args on Windows.
extra – extra keyword arguments are forwarded to the context constructor. See
Context
for more information.
Changed in version 8.0.1: Added the
windows_expand_args
parameter to allow disabling command line arg expansion on Windows.Changed in version 8.0: When taking arguments from
sys.argv
on Windows, glob patterns, user dir, and env vars are expanded.Changed in version 3.0: Added the
standalone_mode
parameter.
- make_context(info_name: str | None, args: List[str], parent: Context | None = None, **extra: Any) Context
This function when given an info name and arguments will kick off the parsing and create a new
Context
. It does not invoke the actual command callback though.To quickly customize the context class used without overriding this method, set the
context_class
attribute.- Parameters:
info_name – the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it’s usually the name of the script, for commands below it’s the name of the command.
args – the arguments to parse as list of strings.
parent – the parent context if available.
extra – extra keyword arguments forwarded to the context constructor.
Changed in version 8.0: Added the
context_class
attribute.
- make_parser(ctx: Context) OptionParser
Creates the underlying option parser for this command.
- parse_args(ctx: Context, args: List[str]) List[str]
Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by
make_context()
.
- result_callback(replace: bool = False) Callable[[F], F]
Adds a result callback to the command. By default if a result callback is already registered this will chain them but this can be disabled with the replace parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback.
Example:
@click.group() @click.option('-i', '--input', default=23) def cli(input): return 42 @cli.result_callback() def process_result(result, input): return result + input
- Parameters:
replace – if set to True an already existing result callback will be removed.
Changed in version 8.0: Renamed from
resultcallback
.New in version 3.0.
- shell_complete(ctx: Context, incomplete: str) List[CompletionItem]
Return a list of completions for the incomplete value. Looks at the names of options, subcommands, and chained multi-commands.
- Parameters:
ctx – Invocation context for this command.
incomplete – Value being completed. May be empty.
New in version 8.0.
- to_info_dict(ctx: Context) Dict[str, Any]
Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire structure below this command.
Use
click.Context.to_info_dict()
to traverse the entire CLI structure.- Parameters:
ctx – A
Context
representing this command.
New in version 8.0.
- DEFAULT_PARAMS = [<Option ip>, <Option token>, <Option model>]
- allow_extra_args = True
the default for the
Context.allow_extra_args
flag.
- allow_interspersed_args = False
the default for the
Context.allow_interspersed_args
flag.
- callback
the callback to execute when the command fires. This might be None in which case nothing happens.
- context_settings: t.MutableMapping[str, t.Any]
an optional dictionary with defaults passed to the context.
- ignore_unknown_options = False
the default for the
Context.ignore_unknown_options
flag.
- name
the name the command thinks it has. Upon registering a command on a
Group
the group will default the command name with this information. You should instead use theContext
'sinfo_name
attribute.
- params: t.List['Parameter']
the list of parameters for this command in the order they should show up in the help page and execute. Eager parameters will automatically be handled before non eager ones.
- class miio.click_common.DeviceGroupMeta(name, bases, namespace)[source]
Bases:
type
- mro()
Return a type’s method resolution order.
- class miio.click_common.EnumType(enumcls, casesensitive=False)[source]
Bases:
Choice
- convert(value, param, ctx)[source]
Convert the value to the correct type. This is not called if the value is
None
(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
param
andctx
arguments may beNone
in certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()
with a descriptive message.- Parameters:
value – The value to convert.
param – The parameter that is using this type to convert its value. May be
None
.ctx – The current context that arrived at this value. May be
None
.
- fail(message: str, param: Parameter | None = None, ctx: Context | None = None) t.NoReturn
Helper method to fail with an invalid value message.
- get_missing_message(param: Parameter) str
Optionally might return extra information about a missing parameter.
New in version 2.0.
- shell_complete(ctx: Context, param: Parameter, incomplete: str) List[CompletionItem]
Complete choices that start with the incomplete value.
- Parameters:
ctx – Invocation context for this command.
param – The parameter that is requesting completion.
incomplete – Value being completed. May be empty.
New in version 8.0.
- split_envvar_value(rv: str) Sequence[str]
Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter.
If the splitter is set to None, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included.
- to_info_dict() Dict[str, Any]
Gather information that could be useful for a tool generating user-facing documentation.
Use
click.Context.to_info_dict()
to traverse the entire CLI structure.New in version 8.0.
- envvar_list_splitter: ClassVar[str | None] = None
if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by
os.path.pathsep
by default (“:” on Unix and “;” on Windows).
- class miio.click_common.ExceptionHandlerGroup(name: str | None = None, commands: MutableMapping[str, Command] | Sequence[Command] | None = None, **attrs: Any)[source]
Bases:
Group
Add a simple group for catching the miio-related exceptions.
This simplifies catching the exceptions from different click commands.
Idea from https://stackoverflow.com/a/44347763
- context_class
alias of
Context
- add_command(cmd: Command, name: str | None = None) None
Registers another
Command
with this group. If the name is not provided, the name of the command is used.
- collect_usage_pieces(ctx: Context) List[str]
Returns all the pieces that go into the usage line and returns it as a list of strings.
- command(*args: Any, **kwargs: Any) Callable[[Callable[[...], Any]], Command] | Command
A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as
command()
and immediately registers the created command with this group by callingadd_command()
.To customize the command class used, set the
command_class
attribute.Changed in version 8.1: This decorator can be applied without parentheses.
Changed in version 8.0: Added the
command_class
attribute.
- format_commands(ctx: Context, formatter: HelpFormatter) None
Extra format methods for multi methods that adds all the commands after the options.
- format_epilog(ctx: Context, formatter: HelpFormatter) None
Writes the epilog into the formatter if it exists.
- format_help(ctx: Context, formatter: HelpFormatter) None
Writes the help into the formatter if it exists.
This is a low-level method called by
get_help()
.This calls the following methods:
- format_help_text(ctx: Context, formatter: HelpFormatter) None
Writes the help text to the formatter if it exists.
- format_options(ctx: Context, formatter: HelpFormatter) None
Writes all the options into the formatter if they exist.
- format_usage(ctx: Context, formatter: HelpFormatter) None
Writes the usage line into the formatter.
This is a low-level method called by
get_usage()
.
- get_command(ctx: Context, cmd_name: str) Command | None
Given a context and a command name, this returns a
Command
object if it exists or returns None.
- get_help(ctx: Context) str
Formats the help into a string and returns it.
Calls
format_help()
internally.
- get_short_help_str(limit: int = 45) str
Gets short help for the command or makes it by shortening the long help string.
- get_usage(ctx: Context) str
Formats the usage line into a string and returns it.
Calls
format_usage()
internally.
- group(*args: Any, **kwargs: Any) Callable[[Callable[[...], Any]], Group] | Group
A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as
group()
and immediately registers the created group with this group by callingadd_command()
.To customize the group class used, set the
group_class
attribute.Changed in version 8.1: This decorator can be applied without parentheses.
Changed in version 8.0: Added the
group_class
attribute.
- invoke(ctx: Context) Any
Given a context, this invokes the attached callback (if it exists) in the right way.
- list_commands(ctx: Context) List[str]
Returns a list of subcommand names in the order they should appear.
- main(args: Sequence[str] | None = None, prog_name: str | None = None, complete_var: str | None = None, standalone_mode: bool = True, windows_expand_args: bool = True, **extra: Any) Any
This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted,
SystemExit
needs to be caught.This method is also available by directly calling the instance of a
Command
.- Parameters:
args – the arguments that should be used for parsing. If not provided,
sys.argv[1:]
is used.prog_name – the program name that should be used. By default the program name is constructed by taking the file name from
sys.argv[0]
.complete_var – the environment variable that controls the bash completion support. The default is
"_<prog_name>_COMPLETE"
with prog_name in uppercase.standalone_mode – the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to False they will be propagated to the caller and the return value of this function is the return value of
invoke()
.windows_expand_args – Expand glob patterns, user dir, and env vars in command line args on Windows.
extra – extra keyword arguments are forwarded to the context constructor. See
Context
for more information.
Changed in version 8.0.1: Added the
windows_expand_args
parameter to allow disabling command line arg expansion on Windows.Changed in version 8.0: When taking arguments from
sys.argv
on Windows, glob patterns, user dir, and env vars are expanded.Changed in version 3.0: Added the
standalone_mode
parameter.
- make_context(info_name: str | None, args: List[str], parent: Context | None = None, **extra: Any) Context
This function when given an info name and arguments will kick off the parsing and create a new
Context
. It does not invoke the actual command callback though.To quickly customize the context class used without overriding this method, set the
context_class
attribute.- Parameters:
info_name – the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it’s usually the name of the script, for commands below it’s the name of the command.
args – the arguments to parse as list of strings.
parent – the parent context if available.
extra – extra keyword arguments forwarded to the context constructor.
Changed in version 8.0: Added the
context_class
attribute.
- make_parser(ctx: Context) OptionParser
Creates the underlying option parser for this command.
- parse_args(ctx: Context, args: List[str]) List[str]
Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by
make_context()
.
- result_callback(replace: bool = False) Callable[[F], F]
Adds a result callback to the command. By default if a result callback is already registered this will chain them but this can be disabled with the replace parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback.
Example:
@click.group() @click.option('-i', '--input', default=23) def cli(input): return 42 @cli.result_callback() def process_result(result, input): return result + input
- Parameters:
replace – if set to True an already existing result callback will be removed.
Changed in version 8.0: Renamed from
resultcallback
.New in version 3.0.
- shell_complete(ctx: Context, incomplete: str) List[CompletionItem]
Return a list of completions for the incomplete value. Looks at the names of options, subcommands, and chained multi-commands.
- Parameters:
ctx – Invocation context for this command.
incomplete – Value being completed. May be empty.
New in version 8.0.
- to_info_dict(ctx: Context) Dict[str, Any]
Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire structure below this command.
Use
click.Context.to_info_dict()
to traverse the entire CLI structure.- Parameters:
ctx – A
Context
representing this command.
New in version 8.0.
- allow_extra_args = True
the default for the
Context.allow_extra_args
flag.
- allow_interspersed_args = False
the default for the
Context.allow_interspersed_args
flag.
- callback
the callback to execute when the command fires. This might be None in which case nothing happens.
- command_class: Type[Command] | None = None
If set, this is used by the group’s
command()
decorator as the defaultCommand
class. This is useful to make all subcommands use a custom command class.New in version 8.0.
- context_settings: t.MutableMapping[str, t.Any]
an optional dictionary with defaults passed to the context.
- group_class: Type[Group] | Type[type] | None = None
If set, this is used by the group’s
group()
decorator as the defaultGroup
class. This is useful to make all subgroups use a custom group class.If set to the special value
type
(literallygroup_class = type
), this group’s class will be used as the default class. This makes a custom group class continue to make custom groups.New in version 8.0.
- ignore_unknown_options = False
the default for the
Context.ignore_unknown_options
flag.
- name
the name the command thinks it has. Upon registering a command on a
Group
the group will default the command name with this information. You should instead use theContext
'sinfo_name
attribute.
- params: t.List['Parameter']
the list of parameters for this command in the order they should show up in the help page and execute. Eager parameters will automatically be handled before non eager ones.
- class miio.click_common.GlobalContextObject(debug: int = 0, output: Callable | None = None)[source]
Bases:
object
- class miio.click_common.LiteralParamType[source]
Bases:
ParamType
- convert(value, param, ctx)[source]
Convert the value to the correct type. This is not called if the value is
None
(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
param
andctx
arguments may beNone
in certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()
with a descriptive message.- Parameters:
value – The value to convert.
param – The parameter that is using this type to convert its value. May be
None
.ctx – The current context that arrived at this value. May be
None
.
- fail(message: str, param: Parameter | None = None, ctx: Context | None = None) t.NoReturn
Helper method to fail with an invalid value message.
- get_metavar(param: Parameter) str | None
Returns the metavar default for this param if it provides one.
- get_missing_message(param: Parameter) str | None
Optionally might return extra information about a missing parameter.
New in version 2.0.
- shell_complete(ctx: Context, param: Parameter, incomplete: str) List[CompletionItem]
Return a list of
CompletionItem
objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.- Parameters:
ctx – Invocation context for this command.
param – The parameter that is requesting completion.
incomplete – Value being completed. May be empty.
New in version 8.0.
- split_envvar_value(rv: str) Sequence[str]
Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter.
If the splitter is set to None, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included.
- to_info_dict() Dict[str, Any]
Gather information that could be useful for a tool generating user-facing documentation.
Use
click.Context.to_info_dict()
to traverse the entire CLI structure.New in version 8.0.
- envvar_list_splitter: ClassVar[str | None] = None
if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by
os.path.pathsep
by default (“:” on Unix and “;” on Windows).