Cliff 类参考

Application

App

class cliff.app.App(description: str | None, version: str | None, command_manager: _commandmanager.CommandManager, stdin: TextIO | None = None, stdout: TextIO | None = None, stderr: TextIO | None = None, interactive_app_factory: type[_interactive.InteractiveApp] | None = None, deferred_help: bool = False)

Application base class.

参数:
  • description (str) – one-liner explaining the program purpose

  • version (str) – application version number

  • command_manager (cliff.commandmanager.CommandManager) – plugin loader

  • stdin (readable I/O stream) – Standard input stream

  • stdout (writable I/O stream) – Standard output stream

  • stderr (writable I/O stream) – Standard error output stream

  • interactive_app_factory (cliff.interactive.InteractiveApp) – callable to create an interactive application

  • deferred_help (bool) – True - Allow subcommands to accept –help with allowing to defer help print after initialize_app

build_option_parser(description: str | None, version: str | None, argparse_kwargs: dict[str, Any] | None = None) ArgumentParser

返回此应用程序的 argparse 选项解析器。

子类可以覆盖此方法以使用更多全局选项扩展解析器。

参数:
  • description (str) – 应用程序的完整描述

  • version (str) – 应用程序的版本号

  • argparse_kwargs – 传递给 ArgumentParser 构造函数的额外关键字参数

clean_up(cmd: _command.Command, result: int, err: BaseException | None) None

Hook run after a command is done to shutdown the app.

参数:
  • cmd (cliff.command.Command) – command processor being invoked

  • result (int) – return value of cmd

  • err (Exception) – exception or None

configure_logging() None

Create logging handlers for any log output.

get_fuzzy_matches(cmd: str) list[str]

return fuzzy matches of unknown command

initialize_app(argv: list[str]) None

子类钩子,用于在解析参数后但在运行命令之前执行全局初始化操作。即使在交互模式下也仅调用一次。

参数:

argv – 参数列表,包括要运行的子命令。对于交互模式为空。

prepare_to_run_command(cmd: _command.Command) None

Perform any preliminary work needed to run a command.

参数:

cmd (cliff.command.Command) – command processor being invoked

print_help_if_requested() None

Print help and exits if deferred help is enabled and requested.

‘–help’ shows the help message and exits
  • without calling initialize_app if not self.deferred_help (default),

  • after initialize_app call if self.deferred_help,

  • during initialize_app call if self.deferred_help and subclass calls explicitly this method in initialize_app.

run(argv: list[str]) int

Equivalent to the main program for the application.

参数:

argv (list of str) – input arguments and options

InteractiveApp

class cliff.interactive.InteractiveApp(parent_app: _app.App, command_manager: _commandmanager.CommandManager, stdin: TextIO | None, stdout: TextIO | None, errexit: bool = False)

Provides “interactive mode” features.

Refer to the cmd2 and cmd documentation for details about subclassing and configuring this class.

参数:
cmdloop(intro: str | None = None) None

Deal with extra features provided by cmd2, this is an outer wrapper around _cmdloop().

_cmdloop() provides the main loop equivalent to cmd.cmdloop(). This is a wrapper around that which deals with the following extra features provided by cmd2: - transcript testing - intro banner - exit code

参数:

intro – if provided this overrides self.intro and serves as the intro banner printed once at start

completedefault(text: str, line: str, begidx: int, endidx: int) list[str]

Default tab-completion for command prefix with completer delimiter.

This method filters only cliff style commands matching provided command prefix (line) as cmd2 style commands cannot contain spaces. This method returns text + missing command part of matching commands. This method does not handle options in cmd2/cliff style commands, you must define complete_$method to handle them.

completenames(text: str, *ignored: Any) list[str]

Tab-completion for command prefix without completer delimiter.

This method returns cmd style and cliff style commands matching provided command prefix (text).

default(line: str) bool | None

Execute when the command given isn’t a recognized command implemented by a do_* method.

参数:

statement – Statement object with parsed input

do_exit(_: Namespace) bool | None

Exit this application.

do_help(arg: str | None) None

List available commands or provide detailed help for a specific command.

get_names() list[str]

Return an alphabetized list of names comprising the attributes of the cmd2 class instance.

precmd(statement: Statement | str) Statement

Hook method executed just before the command is executed by onecmd() and after adding it to history.

参数:

statement – subclass of str which also contains the parsed input

返回值:

a potentially modified version of the input Statement object

CommandManager

class cliff.commandmanager.CommandManager(namespace: str, convert_underscores: bool = True)

Discovers commands and handles lookup based on argv data.

参数:
  • namespace – String containing the entrypoint namespace for the plugins to be loaded. For example, 'cliff.formatter.list'.

  • convert_underscores – Whether cliff should convert underscores to spaces in entry_point commands.

add_command_group(group: str | None = None) None

Adds another group of command entrypoints

add_legacy_command(old_name: str, new_name: str) None

Map an old command name to the new name.

参数:
  • old_name (str) – The old command name.

  • new_name (str) – The new command name.

find_command(argv: list[str]) tuple[type[Command], str, list[str]]

Given an argument list, find a command and return the processor and any remaining arguments.

get_command_groups() list[str]

Returns a list of the loaded command groups

get_command_names(group: str | None = None) list[str]

Returns a list of commands loaded for the specified group

load_commands(namespace: str) None

Load all the commands from an entrypoint

Command

class cliff.command.Command(app: _app.App, app_args: Namespace | None, cmd_name: str | None = None)

Base class for command plugins.

When the command is instantiated, it loads extensions from a namespace based on the parent application namespace and the command name

app.namespace + '.' + cmd_name.replace(' ', '_')
参数:
  • app – Application instance invoking the command.

  • app_args – Parsed arguments from options associated with the application instance..

  • cmd_name – The name of the command.

get_description() str

Return the command description.

The default is to use the first line of the class’ docstring as the description. Set the _description class attribute to a one-line description of a command to use a different value. This is useful for enabling translations, for example, with _description set to a string wrapped with a gettext translation marker.

get_epilog() str

Return the command epilog.

get_parser(prog_name: str) ArgumentParser

返回一个 argparse.ArgumentParser

run(parsed_args: Namespace) int

Invoked by the application when the command is run.

Developers implementing commands should override take_action().

Developers creating new command base classes (such as Lister and ShowOne) should override this method to wrap take_action().

Return the value returned by take_action() or 0.

abstract take_action(parsed_args: Namespace) Any

覆盖以执行有用的操作。

返回值将由程序返回。

CommandHook

class cliff.hooks.CommandHook(command: Command)

Base class for command hooks.

Hook methods are executed in the following order

  1. get_epilog()

  2. get_parser()

  3. before()

  4. after()

参数:

command – Command instance being invoked

abstract after(parsed_args: Namespace, return_code: int) int

Called after the command’s take_action() method.

参数:
  • parsed_args – The arguments to the command.

  • return_code (int) – The value returned from take_action().

返回值:

int

abstract before(parsed_args: Namespace) Namespace

Called before the command’s take_action() method.

参数:

parsed_args – The arguments to the command.

返回值:

argparse.Namespace

abstract get_epilog() str | None

Return text to add to the command help epilog.

返回值:

An epilog string or None.

abstract get_parser(parser: ArgumentParser) ArgumentParser | None

Modify the command argparse.ArgumentParser.

The provided parser is modified in-place, and the return value is not used.

参数:

parser – An existing ArgumentParser instance to be modified.

返回值:

ArgumentParser or None

ShowOne

class cliff.show.ShowOne(app: App, app_args: Namespace | None, cmd_name: str | None = None)

Command base class for displaying data about a single object.

dict2columns(data: dict[str, Any]) tuple[tuple[str, ...], tuple[Any, ...]]

Implement the common task of converting a dict-based object to the two-column output that ShowOne expects.

property formatter_default: str

String specifying the name of the default formatter.

property formatter_namespace: str

String specifying the namespace to use for loading formatter plugins.

produce_output(parsed_args: Namespace, column_names: Sequence[str], data: Iterable[Sequence[Any]]) int

Use the formatter to generate the output.

参数:
  • parsed_args – argparse.Namespace instance with argument values

  • column_names – sequence of strings containing names of output columns

  • data – iterable with values matching the column names

返回值:

a status code

abstract take_action(parsed_args: Namespace) tuple[tuple[str, ...], tuple[Any, ...]]

返回一个包含列名元组和包含要列出的数据的可迭代元组。

Lister

class cliff.lister.Lister(app: App, app_args: Namespace | None, cmd_name: str | None = None)

Command base class for providing a list of data as output.

property formatter_default: str

String specifying the name of the default formatter.

property formatter_namespace: str

String specifying the namespace to use for loading formatter plugins.

get_parser(prog_name: str) ArgumentParser

返回一个 argparse.ArgumentParser

property need_sort_by_cliff: bool

Whether sort procedure is performed by cliff itself.

Should be overridden (return False) when there is a need to implement custom sorting procedure or data is already sorted.

produce_output(parsed_args: Namespace, column_names: Sequence[str], data: Iterable[Sequence[Any]]) int

Use the formatter to generate the output.

参数:
  • parsed_args – argparse.Namespace instance with argument values

  • column_names – sequence of strings containing names of output columns

  • data – iterable with values matching the column names

返回值:

a status code

abstract take_action(parsed_args: Namespace) tuple[Sequence[str], Iterable[Any]]

运行命令。

返回一个元组,包含列名和一个包含要列出的数据的可迭代对象。

Formatting Output

Formatter

class cliff.formatters.base.Formatter
abstract add_argument_group(parser: ArgumentParser) None

Add any options to the argument parser.

Should use our own argument group.

ListFormatter

class cliff.formatters.base.ListFormatter

Base class for formatters that know how to deal with multiple objects.

abstract emit_list(column_names: Sequence[str], data: Iterable[Sequence[Any]], stdout: TextIO, parsed_args: Namespace) None

Format and print the list from the iterable data source.

Data values can be primitive types like ints and strings, or can be an instance of a FormattableColumn for situations where the value is complex, and may need to be handled differently for human readable output vs. machine readable output.

参数:
  • column_names – names of the columns

  • data – iterable data source, one tuple per object with values in order of column names

  • stdout – output stream where data should be written

  • parsed_args – argparse namespace from our local options

SingleFormatter

class cliff.formatters.base.SingleFormatter

Base class for formatters that work with single objects.

abstract emit_one(column_names: Sequence[str], data: Sequence[Any], stdout: TextIO, parsed_args: Namespace) None

Format and print the values associated with the single object.

Data values can be primitive types like ints and strings, or can be an instance of a FormattableColumn for situations where the value is complex, and may need to be handled differently for human readable output vs. machine readable output.

参数:
  • column_names – names of the columns

  • data – iterable data source with values in order of column names

  • stdout – output stream where data should be written

  • parsed_args – argparse namespace from our local options