Skip to content

Commit d25fd71

Browse files
authored
Merge pull request #899 from python-cmd2/api_docs
API documentation
2 parents fea1bc1 + 803f71a commit d25fd71

32 files changed

+990
-569
lines changed

cmd2/ansi.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,33 @@
1717

1818
# Values for allow_style setting
1919
STYLE_NEVER = 'Never'
20+
"""
21+
Constant for ``cmd2.ansi.allow_style`` to indicate ANSI sequences
22+
should be removed from all output.
23+
"""
2024
STYLE_TERMINAL = 'Terminal'
25+
"""
26+
Constant for ``cmd2.ansi.allow_style`` to indicate ANSI sequences
27+
should be removed if the output is not going to the terminal.
28+
"""
2129
STYLE_ALWAYS = 'Always'
30+
"""
31+
Constant for ``cmd2.ansi.allow_style`` to indicate ANSI sequences
32+
should alwyas be output.
33+
"""
2234

2335
# Controls when ANSI style style sequences are allowed in output
2436
allow_style = STYLE_TERMINAL
37+
"""When using outside of a cmd2 app, set this variable to one of:
38+
39+
- ``STYLE_NEVER`` - remove ANSI sequences from all output
40+
- ``STYLE_TERMINAL`` - remove ANSI sequences if the output is not going to the terminal
41+
- ``STYLE_ALWAYS`` - always output ANSI sequences
42+
43+
to control the output of ANSI sequences by methods in this module.
44+
45+
The default is ``STYLE_TERMINAL``.
46+
"""
2547

2648
# Regular expression to match ANSI style sequences (including 8-bit and 24-bit colors)
2749
ANSI_STYLE_RE = re.compile(r'\x1b\[[^m]*m')
@@ -32,7 +54,9 @@ class ColorBase(Enum):
3254
Base class used for defining color enums. See fg and bg classes for examples.
3355
3456
Child classes should define enums in the follow structure:
57+
3558
key: color name (e.g. black)
59+
3660
value: anything that when cast to a string returns an ANSI sequence
3761
"""
3862
def __str__(self) -> str:
@@ -111,17 +135,25 @@ class bg(ColorBase):
111135

112136

113137
FG_RESET = fg.reset.value
138+
"""ANSI sequence to reset the foreground attributes"""
114139
BG_RESET = bg.reset.value
140+
"""ANSI sequence to reset the terminal background attributes"""
115141
RESET_ALL = Style.RESET_ALL
142+
"""ANSI sequence to reset all terminal attributes"""
116143

117144
# Text intensities
118145
INTENSITY_BRIGHT = Style.BRIGHT
146+
"""ANSI sequence to make the text bright"""
119147
INTENSITY_DIM = Style.DIM
148+
"""ANSI sequence to make the text dim"""
120149
INTENSITY_NORMAL = Style.NORMAL
150+
"""ANSI sequence to make the text normal"""
121151

122152
# ANSI style sequences not provided by colorama
123153
UNDERLINE_ENABLE = colorama.ansi.code_to_chars(4)
154+
"""ANSI sequence to turn on underline"""
124155
UNDERLINE_DISABLE = colorama.ansi.code_to_chars(24)
156+
"""ANSI sequence to turn off underline"""
125157

126158

127159
def strip_style(text: str) -> str:

cmd2/argparse_custom.py

Lines changed: 173 additions & 142 deletions
Large diffs are not rendered by default.

cmd2/cmd2.py

Lines changed: 77 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -135,28 +135,41 @@ def __init__(self, completekey: str = 'tab', stdin=None, stdout=None, *,
135135
allow_cli_args: bool = True, transcript_files: Optional[List[str]] = None,
136136
allow_redirection: bool = True, multiline_commands: Optional[List[str]] = None,
137137
terminators: Optional[List[str]] = None, shortcuts: Optional[Dict[str, str]] = None) -> None:
138-
"""An easy but powerful framework for writing line-oriented command interpreters, extends Python's cmd package.
138+
"""An easy but powerful framework for writing line-oriented command
139+
interpreters. Extends Python's cmd package.
139140
140141
:param completekey: readline name of a completion key, default to Tab
141142
:param stdin: alternate input file object, if not specified, sys.stdin is used
142143
:param stdout: alternate output file object, if not specified, sys.stdout is used
143144
:param persistent_history_file: file path to load a persistent cmd2 command history from
144-
:param persistent_history_length: max number of history items to write to the persistent history file
145+
:param persistent_history_length: max number of history items to write
146+
to the persistent history file
145147
:param startup_script: file path to a script to execute at startup
146148
:param use_ipython: should the "ipy" command be included for an embedded IPython shell
147-
:param allow_cli_args: if True, then cmd2 will process command line arguments as either
148-
commands to be run or, if -t is specified, transcript files to run.
149-
This should be set to False if your application parses its own arguments.
150-
:param transcript_files: allow running transcript tests when allow_cli_args is False
151-
:param allow_redirection: should output redirection and pipes be allowed. this is only a security setting
152-
and does not alter parsing behavior.
149+
:param allow_cli_args: if ``True``, then :meth:`cmd2.Cmd.__init__` will process command
150+
line arguments as either commands to be run or, if ``-t`` or
151+
``--test`` are given, transcript files to run. This should be
152+
set to ``False`` if your application parses its own command line
153+
arguments.
154+
:param transcript_files: pass a list of transcript files to be run on initialization.
155+
This allows running transcript tests when ``allow_cli_args``
156+
is ``False``. If ``allow_cli_args`` is ``True`` this parameter
157+
is ignored.
158+
:param allow_redirection: If ``False``, prevent output redirection and piping to shell
159+
commands. This parameter prevents redirection and piping, but
160+
does not alter parsing behavior. A user can still type
161+
redirection and piping tokens, and they will be parsed as such
162+
but they won't do anything.
153163
:param multiline_commands: list of commands allowed to accept multi-line input
154-
:param terminators: list of characters that terminate a command. These are mainly intended for terminating
155-
multiline commands, but will also terminate single-line commands. If not supplied, then
156-
defaults to semicolon. If your app only contains single-line commands and you want
157-
terminators to be treated as literals by the parser, then set this to an empty list.
158-
:param shortcuts: dictionary containing shortcuts for commands. If not supplied, then defaults to
159-
constants.DEFAULT_SHORTCUTS.
164+
:param terminators: list of characters that terminate a command. These are mainly
165+
intended for terminating multiline commands, but will also
166+
terminate single-line commands. If not supplied, the default
167+
is a semicolon. If your app only contains single-line commands
168+
and you want terminators to be treated as literals by the parser,
169+
then set this to an empty list.
170+
:param shortcuts: dictionary containing shortcuts for commands. If not supplied,
171+
then defaults to constants.DEFAULT_SHORTCUTS. If you do not want
172+
any shortcuts, pass an empty dictionary.
160173
"""
161174
# If use_ipython is False, make sure the ipy command isn't available in this instance
162175
if not use_ipython:
@@ -192,7 +205,7 @@ def __init__(self, completekey: str = 'tab', stdin=None, stdout=None, *,
192205

193206
# A dictionary mapping settable names to their Settable instance
194207
self.settables = dict()
195-
self.build_settables()
208+
self._build_settables()
196209

197210
# Use as prompt for multiline commands on the 2nd+ line of input
198211
self.continuation_prompt = '> '
@@ -374,24 +387,26 @@ def __init__(self, completekey: str = 'tab', stdin=None, stdout=None, *,
374387

375388
def add_settable(self, settable: Settable) -> None:
376389
"""
377-
Convenience method to add a settable parameter to self.settables
390+
Convenience method to add a settable parameter to ``self.settables``
391+
378392
:param settable: Settable object being added
379393
"""
380394
self.settables[settable.name] = settable
381395

382396
def remove_settable(self, name: str) -> None:
383397
"""
384-
Convenience method for removing a settable parameter from self.settables
398+
Convenience method for removing a settable parameter from ``self.settables``
399+
385400
:param name: name of the settable being removed
386-
:raises: KeyError if the no Settable matches this name
401+
:raises: KeyError if the Settable matches this name
387402
"""
388403
try:
389404
del self.settables[name]
390405
except KeyError:
391406
raise KeyError(name + " is not a settable parameter")
392407

393-
def build_settables(self):
394-
"""Populates self.add_settable with parameters that can be edited via the set command"""
408+
def _build_settables(self):
409+
"""Construct the default settings"""
395410
self.add_settable(Settable('allow_style', str,
396411
'Allow ANSI text style sequences in output (valid values: '
397412
'{}, {}, {})'.format(ansi.STYLE_TERMINAL,
@@ -1508,13 +1523,54 @@ def sigint_handler(self, signum: int, frame) -> None:
15081523
raise KeyboardInterrupt("Got a keyboard interrupt")
15091524

15101525
def precmd(self, statement: Statement) -> Statement:
1511-
"""Hook method executed just before the command is processed by ``onecmd()`` and after adding it to the history.
1526+
"""Hook method executed just before the command is executed by
1527+
:meth:`~cmd2.Cmd.onecmd` and after adding it to history.
15121528
15131529
:param statement: subclass of str which also contains the parsed input
15141530
:return: a potentially modified version of the input Statement object
1531+
1532+
See :meth:`~cmd2.Cmd.register_postparsing_hook` and
1533+
:meth:`~cmd2.Cmd.register_precmd_hook` for more robust ways
1534+
to run hooks before the command is executed. See
1535+
:ref:`features/hooks:Postparsing Hooks` and
1536+
:ref:`features/hooks:Precommand Hooks` for more information.
15151537
"""
15161538
return statement
15171539

1540+
def postcmd(self, stop: bool, statement: Statement) -> bool:
1541+
"""Hook method executed just after a command is executed by
1542+
:meth:`~cmd2.Cmd.onecmd`.
1543+
1544+
:param stop: return `True` to request the command loop terminate
1545+
:param statement: subclass of str which also contains the parsed input
1546+
1547+
See :meth:`~cmd2.Cmd.register_postcmd_hook` and :meth:`~cmd2.Cmd.register_cmdfinalization_hook` for more robust ways
1548+
to run hooks after the command is executed. See
1549+
:ref:`features/hooks:Postcommand Hooks` and
1550+
:ref:`features/hooks:Command Finalization Hooks` for more information.
1551+
"""
1552+
return stop
1553+
1554+
def preloop(self):
1555+
"""Hook method executed once when the :meth:`~.cmd2.Cmd.cmdloop()`
1556+
method is called.
1557+
1558+
See :meth:`~cmd2.Cmd.register_preloop_hook` for a more robust way
1559+
to run hooks before the command loop begins. See
1560+
:ref:`features/hooks:Application Lifecycle Hooks` for more information.
1561+
"""
1562+
pass
1563+
1564+
def postloop(self):
1565+
"""Hook method executed once when the :meth:`~.cmd2.Cmd.cmdloop()`
1566+
method is about to return.
1567+
1568+
See :meth:`~cmd2.Cmd.register_postloop_hook` for a more robust way
1569+
to run hooks after the command loop completes. See
1570+
:ref:`features/hooks:Application Lifecycle Hooks` for more information.
1571+
"""
1572+
pass
1573+
15181574
def parseline(self, line: str) -> Tuple[str, str, str]:
15191575
"""Parse the line into a command name and a string containing the arguments.
15201576

cmd2/constants.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
#
22
# coding=utf-8
3-
"""Constants and definitions"""
3+
"""This module contains constants used throughout ``cmd2``."""
4+
5+
# Unless documented in https://cmd2.readthedocs.io/en/latest/api/index.html
6+
# nothing here should be considered part of the public API of this module
7+
48

59
# Used for command parsing, output redirection, tab completion and word
610
# breaks. Do not change.
@@ -32,9 +36,9 @@
3236
# All command completer functions start with this
3337
COMPLETER_FUNC_PREFIX = 'complete_'
3438

35-
############################################################################################################
39+
##############################################################################
3640
# The following are optional attributes added to do_* command functions
37-
############################################################################################################
41+
##############################################################################
3842

3943
# The custom help category a command belongs to
4044
CMD_ATTR_HELP_CATEGORY = 'help_category'

cmd2/decorators.py

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,21 @@
88

99

1010
def with_category(category: str) -> Callable:
11-
"""A decorator to apply a category to a command function."""
11+
"""A decorator to apply a category to a ``do_*`` command method.
12+
13+
:param category: the name of the category in which this command should
14+
be grouped when displaying the list of commands.
15+
16+
:Example:
17+
18+
>>> class MyApp(cmd2.Cmd):
19+
>>> @cmd2.with_category('Text Functions')
20+
>>> def do_echo(self, args)
21+
>>> self.poutput(args)
22+
23+
For an alternative approach to categorizing commands using a function, see
24+
:func:`~cmd2.utils.categorize`
25+
"""
1226
def cat_decorator(func):
1327
from .utils import categorize
1428
categorize(func, category)
@@ -17,12 +31,22 @@ def cat_decorator(func):
1731

1832

1933
def with_argument_list(*args: List[Callable], preserve_quotes: bool = False) -> Callable[[List], Optional[bool]]:
20-
"""A decorator to alter the arguments passed to a do_* cmd2 method. Default passes a string of whatever the user
21-
typed. With this decorator, the decorated method will receive a list of arguments parsed from user input.
34+
"""
35+
A decorator to alter the arguments passed to a ``do_*`` method. Default
36+
passes a string of whatever the user typed. With this decorator, the
37+
decorated method will receive a list of arguments parsed from user input.
2238
23-
:param args: Single-element positional argument list containing do_* method this decorator is wrapping
24-
:param preserve_quotes: if True, then argument quotes will not be stripped
39+
:param args: Single-element positional argument list containing ``do_*`` method
40+
this decorator is wrapping
41+
:param preserve_quotes: if ``True``, then argument quotes will not be stripped
2542
:return: function that gets passed a list of argument strings
43+
44+
:Example:
45+
46+
>>> class MyApp(cmd2.Cmd):
47+
>>> @cmd2.with_argument_list
48+
>>> def do_echo(self, arglist):
49+
>>> self.poutput(' '.join(arglist)
2650
"""
2751
import functools
2852

@@ -75,18 +99,19 @@ def with_argparser_and_unknown_args(parser: argparse.ArgumentParser, *,
7599
ns_provider: Optional[Callable[..., argparse.Namespace]] = None,
76100
preserve_quotes: bool = False) -> \
77101
Callable[[argparse.Namespace, List], Optional[bool]]:
78-
"""A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given
79-
instance of argparse.ArgumentParser, but also returning unknown args as a list.
102+
"""A decorator to alter a cmd2 method to populate its ``args`` argument by parsing
103+
arguments with the given instance of argparse.ArgumentParser, but also returning
104+
unknown args as a list.
80105
81106
:param parser: unique instance of ArgumentParser
82-
:param ns_provider: An optional function that accepts a cmd2.Cmd object as an argument and returns an
83-
argparse.Namespace. This is useful if the Namespace needs to be prepopulated with
84-
state data that affects parsing.
85-
:param preserve_quotes: if True, then arguments passed to argparse maintain their quotes
86-
:return: function that gets passed argparse-parsed args in a Namespace and a list of unknown argument strings
87-
A member called __statement__ is added to the Namespace to provide command functions access to the
88-
Statement object. This can be useful if the command function needs to know the command line.
89-
107+
:param ns_provider: An optional function that accepts a cmd2.Cmd object as an argument
108+
and returns an argparse.Namespace. This is useful if the Namespace
109+
needs to be prepopulated with state data that affects parsing.
110+
:param preserve_quotes: if ``True``, then arguments passed to argparse maintain their quotes
111+
:return: function that gets passed argparse-parsed args in a ``Namespace`` and a list
112+
of unknown argument strings. A member called ``__statement__`` is added to the
113+
``Namespace`` to provide command functions access to the :class:`cmd2.Statement`
114+
object. This can be useful if the command function needs to know the command line.
90115
"""
91116
import functools
92117

0 commit comments

Comments
 (0)