Skip to content

Commit 7460055

Browse files
committed
Starting to give the documentation a very thorough review
1 parent 9d8e9e6 commit 7460055

14 files changed

+194
-172
lines changed

docs/features/argument_processing.md

Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,20 @@
44
[argparse](https://docs.python.org/3/library/argparse.html) python module. `cmd2` handles the
55
following for you:
66

7-
1. Parsing input and quoted strings like the Unix shell
8-
1. Parse the resulting argument list using an instance of `argparse.ArgumentParser` that you provide
9-
1. Passes the resulting `argparse.Namespace` object to your command function. The `Namespace`
10-
includes the `Statement` object that was created when parsing the command line. It can be
11-
retrieved by calling `cmd2_statement.get()` on the `Namespace`.
7+
1. Parsing input and quoted strings in a manner similar to how POSIX shells do it
8+
1. Parse the resulting argument list using an instance of
9+
[argparse.ArgumentParser](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser)
10+
that you provide
11+
1. Passes the resulting
12+
[argparse.Namespace](https://docs.python.org/3/library/argparse.html#argparse.Namespace) object
13+
to your command function. The `Namespace` includes the [Statement][cmd2.Statement] object that
14+
was created when parsing the command line. It can be retrieved by calling `cmd2_statement.get()`
15+
on the `Namespace`.
1216
1. Adds the usage message from the argument parser to your command's help.
1317
1. Checks if the `-h/--help` option is present, and if so, displays the help message for the command
1418

15-
These features are all provided by the `@with_argparser` decorator which is imported from `cmd2`.
19+
These features are all provided by the [@with_argparser][cmd2.with_argparser] decorator which is
20+
imported from `cmd2`.
1621

1722
See the
1823
[argparse_example](https://github.com/python-cmd2/cmd2/blob/main/examples/argparse_example.py)
@@ -31,11 +36,11 @@ command which might have its own argument parsing.
3136

3237
## Argument Parsing
3338

34-
For each command in the `cmd2` subclass which requires argument parsing, create a unique instance of
35-
`argparse.ArgumentParser()` which can parse the input appropriately for the command. Then decorate
36-
the command method with the `@with_argparser` decorator, passing the argument parser as the first
37-
parameter to the decorator. This changes the second argument to the command method, which will
38-
contain the results of `ArgumentParser.parse_args()`.
39+
For each command in the `cmd2.Cmd` subclass which requires argument parsing, create a unique
40+
instance of `argparse.ArgumentParser()` which can parse the input appropriately for the command.
41+
Then decorate the command method with the `@with_argparser` decorator, passing the argument parser
42+
as the first parameter to the decorator. This changes the second argument to the command method,
43+
which will contain the results of `ArgumentParser.parse_args()`.
3944

4045
Here's what it looks like:
4146

@@ -65,8 +70,8 @@ def do_speak(self, opts):
6570

6671
`cmd2` sets the `prog` variable in the argument parser based on the name of the method it is decorating. This will override anything you specify in `prog` variable when creating the argument parser.
6772

68-
As of the 3.0.0 release, `cmd2` sets `prog` when the instance-specific parser is created, which is
69-
later than it did previously.
73+
As of the 3.0.0 release, `cmd2` sets `prog` when the instance-specific parser is created, which is
74+
later than it did previously.
7075

7176
## Help Messages
7277

@@ -84,7 +89,7 @@ argparser.add_argument('tag', help='tag')
8489
argparser.add_argument('content', nargs='+', help='content to surround with tag')
8590
@with_argparser(argparser)
8691
def do_tag(self, args):
87-
"""create a html tag"""
92+
"""Create an HTML tag"""
8893
self.stdout.write('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content)))
8994
self.stdout.write('\n')
9095
```
@@ -94,7 +99,7 @@ the `help tag` command displays:
9499
```text
95100
usage: tag [-h] tag content [content ...]
96101
97-
create an HTML tag
102+
Create an HTML tag
98103
99104
positional arguments:
100105
tag tag
@@ -168,13 +173,13 @@ This command cannot generate tags with no content, like <br/>
168173

169174
!!! warning
170175

171-
If a command **foo** is decorated with one of cmd2's argparse decorators, then **help_foo** will not be invoked when `help foo` is called. The [argparse](https://docs.python.org/3/library/argparse.html) module provides a rich API which can be used to tweak every aspect of the displayed help and we encourage `cmd2` developers to utilize that.
176+
If a command **foo** is decorated with `cmd2`'s `with_argparse` decorator, then **help_foo** will not be invoked when `help foo` is called. The [argparse](https://docs.python.org/3/library/argparse.html) module provides a rich API which can be used to tweak every aspect of the displayed help and we encourage `cmd2` developers to utilize that.
172177

173178
## Argument List
174179

175180
The default behavior of `cmd2` is to pass the user input directly to your `do_*` methods as a
176-
string. The object passed to your method is actually a `Statement` object, which has additional
177-
attributes that may be helpful, including `arg_list` and `argv`:
181+
string. The object passed to your method is actually a [Statement][cmd2.Statement] object, which has
182+
additional attributes that may be helpful, including `arg_list` and `argv`:
178183

179184
```py
180185
class CmdLineApp(cmd2.Cmd):
@@ -200,8 +205,8 @@ class CmdLineApp(cmd2.Cmd):
200205

201206
If you don't want to access the additional attributes on the string passed to your `do_*` method you
202207
can still have `cmd2` apply shell parsing rules to the user input and pass you a list of arguments
203-
instead of a string. Apply the `@with_argument_list` decorator to those methods that should receive
204-
an argument list instead of a string:
208+
instead of a string. Apply the [@with_argument_list][cmd2.with_argument_list] decorator to those
209+
methods that should receive an argument list instead of a string:
205210

206211
```py
207212
from cmd2 import with_argument_list
@@ -272,7 +277,7 @@ def settings_ns_provider(self) -> argparse.Namespace:
272277
return ns
273278
```
274279

275-
To use this function with the argparse decorators, do the following:
280+
To use this function with the `@2ith_argparser` decorator, do the following:
276281

277282
```py
278283
@with_argparser(my_parser, ns_provider=settings_ns_provider)
@@ -293,14 +298,16 @@ See the
293298
[argparse_example](https://github.com/python-cmd2/cmd2/blob/main/examples/argparse_example.py)
294299
example to learn more about how to use subcommands in your `cmd2` application.
295300

301+
The [@as_subcommand_to][cmd2.as_subcommand_to] decorator makes adding subcommands easy.
302+
296303
## Argparse Extensions
297304

298305
`cmd2` augments the standard `argparse.nargs` with range tuple capability:
299306

300307
- `nargs=(5,)` - accept 5 or more items
301308
- `nargs=(8, 12)` - accept 8 to 12 items
302309

303-
`cmd2` also provides the `cmd2.argparse_custom.Cmd2ArgumentParser` class which inherits from
310+
`cmd2` also provides the [Cmd2ArgumentParser][cmd2.Cmd2ArgumentParser] class which inherits from
304311
`argparse.ArgumentParser` and improves error and help output.
305312

306313
## Decorator Order
@@ -338,8 +345,8 @@ example demonstrates both above cases in a concrete fashion.
338345

339346
## Reserved Argument Names
340347

341-
`cmd2` argparse decorators add the following attributes to argparse Namespaces. To avoid naming
342-
collisions, do not use any of the names for your argparse arguments.
348+
`cmd2`'s `@with_argparser` decorator adds the following attributes to argparse Namespaces. To avoid
349+
naming collisions, do not use any of the names for your argparse arguments.
343350

344351
- `cmd2_statement` - `cmd2.Cmd2AttributeWrapper` object containing the `cmd2.Statement` object that
345352
was created when parsing the command line.

docs/features/builtin_commands.md

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Builtin Commands
22

3-
Applications which subclass `cmd2.Cmd` inherit a number of commands which may be useful to your
3+
Applications which subclass [cmd2.Cmd][] inherit a number of commands which may be useful to your
44
users. Developers can [Remove Builtin Commands](#remove-builtin-commands) if they do not want them
55
to be part of the application.
66

@@ -33,7 +33,7 @@ for more information.
3333
This command allows you to view, run, edit, save, or clear previously entered commands from the
3434
history. See [History](history.md) for more information.
3535

36-
### ipy
36+
### ipy (optional)
3737

3838
This optional opt-in command enters an interactive IPython shell. See
3939
[IPython (optional)](./embedded_python_shells.md#ipython-optional) for more information.
@@ -44,9 +44,9 @@ This command manages macros via subcommands `create`, `delete`, and `list`. A ma
4444
alias, but it can contain argument placeholders. See [Macros](./shortcuts_aliases_macros.md#macros)
4545
for more information.
4646

47-
### py
47+
### py (optional)
4848

49-
This command invokes a Python command or shell. See
49+
This optional opt-in command invokes a Python command or shell. See
5050
[Embedded Python Shells](./embedded_python_shells.md) for more information.
5151

5252
### quit
@@ -63,7 +63,7 @@ This command runs a Python script file inside the `cmd2` application. See
6363
This command runs commands in a script file that is encoded as either ASCII or UTF-8 text. See
6464
[Command Scripts](./scripting.md#command-scripts) for more information.
6565

66-
### \_relative_run_script
66+
### \_relative_run_script (hidden)
6767

6868
This command is hidden from the help that's visible to end users. It runs a script like
6969
[run_script](#run_script) but does so using a path relative to the script that is currently
@@ -77,21 +77,19 @@ application:
7777

7878
```text
7979
(Cmd) set
80-
Name Value Description
81-
====================================================================================================================
82-
allow_style Terminal Allow ANSI text style sequences in output (valid values:
83-
Always, Never, Terminal)
84-
always_show_hint False Display tab completion hint even when completion suggestions
85-
print
86-
debug True Show full traceback on exception
87-
echo False Echo command issued into output
88-
editor vi Program used by 'edit'
89-
feedback_to_output False Include nonessentials in '|' and '>' results
90-
max_completion_items 50 Maximum number of CompletionItems to display during tab
91-
completion
92-
quiet False Don't print non-essential feedback
93-
scripts_add_to_history True Scripts and pyscripts add commands to history
94-
timing False Report execution times
80+
Name Value Description
81+
───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
82+
allow_style Terminal Allow ANSI text style sequences in output (valid values: Always, Never, Terminal)
83+
always_show_hint False Display tab completion hint even when completion suggestions print
84+
debug False Show full traceback on exception
85+
echo False Echo command issued into output
86+
editor vim Program used by 'edit'
87+
feedback_to_output False Include nonessentials in '|' and '>' results
88+
foreground_color cyan Foreground color to use with echo command
89+
max_completion_items 50 Maximum number of CompletionItems to display during tab completion
90+
quiet False Don't print nonessential feedback
91+
scripts_add_to_history True Scripts and pyscripts add commands to history
92+
timing False Report execution times
9593
```
9694

9795
Any of these user-settable parameters can be set while running your app with the `set` command like
@@ -119,10 +117,10 @@ more information.
119117

120118
## Remove Builtin Commands
121119

122-
Developers may not want to offer the commands builtin to [cmd2.Cmd][] to users of their application.
123-
To remove a command you must delete the method implementing that command from the [cmd2.Cmd][]
124-
object at runtime. For example, if you wanted to remove the [shell](#shell) command from your
125-
application:
120+
Developers may not want to offer all the commands built into [cmd2.Cmd][] to users of their
121+
application. To remove a command you must delete the method implementing that command from the
122+
[cmd2.Cmd][] object at runtime. For example, if you wanted to remove the [shell](#shell) command
123+
from your application:
126124

127125
```py
128126
class NoShellApp(cmd2.Cmd):

docs/features/clipboard.md

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# Clipboard Integration
22

33
Nearly every operating system has some notion of a short-term storage area which can be accessed by
4-
any program. Usually this is called the clipboard, but sometimes people refer to it as the paste
5-
buffer.
4+
any program. Usually this is called the :clipboard: clipboard, but sometimes people refer to it as
5+
the paste buffer.
66

77
`cmd2` integrates with the operating system clipboard using the
88
[pyperclip](https://github.com/asweigart/pyperclip) module. Command output can be sent to the
@@ -32,10 +32,4 @@ If you would like your `cmd2` based application to be able to use the clipboard
3232
alternative ways, you can use the following methods (which work uniformly on Windows, macOS, and
3333
Linux).
3434

35-
<!-- prettier-ignore-start -->
3635
::: cmd2.clipboard
37-
handler: python
38-
options:
39-
show_root_heading: false
40-
show_source: false
41-
<!-- prettier-ignore-end -->

docs/features/commands.md

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,16 @@ if __name__ == '__main__':
2828
sys.exit(c.cmdloop())
2929
```
3030

31-
This application subclasses `cmd2.Cmd` but has no code of its own, so all functionality (and there's
32-
quite a bit) is inherited. Let's create a simple command in this application called `echo` which
33-
outputs any arguments given to it. Add this method to the class:
31+
This application subclasses [cmd2.Cmd][] but has no code of its own, so all functionality (and
32+
there's quite a bit) is inherited. Let's create a simple command in this application called `echo`
33+
which outputs any arguments given to it. Add this method to the class:
3434

3535
```py
3636
def do_echo(self, line):
3737
self.poutput(line)
3838
```
3939

40-
When you type input into the `cmd2` prompt, the first space delimited word is treated as the command
40+
When you type input into the `cmd2` prompt, the first space-delimited word is treated as the command
4141
name. `cmd2` looks for a method called `do_commandname`. If it exists, it calls the method, passing
4242
the rest of the user input as the first argument. If it doesn't exist `cmd2` prints an error
4343
message. As a result of this behavior, the only thing you have to do to create a new command is to
@@ -47,13 +47,14 @@ python standard library.
4747

4848
!!! note
4949

50-
See [Generating Output](./generating_output.md) if you are unfamiliar with the `poutput()` method.
50+
See [Generating Output](./generating_output.md) if you are unfamiliar with the
51+
[poutput()][cmd2.Cmd.poutput] method.
5152

5253
## Statements
5354

5455
A command is passed one argument: a string which contains all the rest of the user input. However,
55-
in `cmd2` this string is actually a `Statement` object, which is a subclass of `str` to retain
56-
backwards compatibility.
56+
in `cmd2` this string is actually a [Statement][cmd2.Statement] object, which is a subclass of `str`
57+
to retain backwards compatibility with `cmd`.
5758

5859
`cmd2` has a much more sophisticated parsing engine than what's included in the
5960
[cmd](https://docs.python.org/3/library/cmd.html) module. This parsing handles:
@@ -84,7 +85,7 @@ args
8485
commands removed. It turns out that the "string" value of the `Statement` object has all the output
8586
redirection and piping clauses removed as well. Quotes remain in the string.
8687

87-
command[and_args]{#and_args}
88+
command_and_args
8889

8990
: A string of just the command and the arguments, with output redirection or piping to shell
9091
commands removed.
@@ -116,9 +117,11 @@ Most commands should return nothing (either by omitting a `return` statement, or
116117
This indicates that your command is finished (with or without errors), and that `cmd2` should prompt
117118
the user for more input.
118119

119-
If you return `True` from a command method, that indicates to `cmd2` that it should stop prompting
120-
for user input and cleanly exit. `cmd2` already includes a `quit` command, but if you wanted to make
121-
another one called `finish` you could:
120+
If you return `True` or any
121+
[Truthy](https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/) value from a command
122+
method, that indicates to `cmd2` that it should stop prompting for user input and cleanly exit.
123+
`cmd2` already includes a `quit` command, but if you wanted to make another one called `finish` you
124+
could:
122125

123126
```py
124127
def do_finish(self, line):
@@ -128,11 +131,11 @@ def do_finish(self, line):
128131

129132
## Exit Codes
130133

131-
`cmd2` has basic infrastructure to support sh/ksh/csh/bash type exit codes. The `cmd2.Cmd` object
132-
sets an `exit_code` attribute to zero when it is instantiated. The value of this attribute is
133-
returned from the `cmdloop()` call. Therefore, if you don't do anything with this attribute in your
134-
code, `cmdloop()` will (almost) always return zero. There are a few built-in `cmd2` commands which
135-
set `exit_code` to `1` if an error occurs.
134+
`cmd2` has basic infrastructure to support POSIX shell exit codes. The `cmd2.Cmd` object sets an
135+
`exit_code` attribute to zero when it is instantiated. The value of this attribute is returned from
136+
the `cmdloop()` call. Therefore, if you don't do anything with this attribute in your code,
137+
`cmdloop()` will (almost) always return zero. There are a few built-in `cmd2` commands which set
138+
`exit_code` to `1` if an error occurs.
136139

137140
You can use this capability to easily return your own values to the operating system shell:
138141

@@ -192,13 +195,13 @@ All other `BaseExceptions` are not caught by `cmd2` and will be raised.
192195

193196
See [Disabling Commands](./disable_commands.md) for details of how to:
194197

195-
- remove commands included in `cmd2`
196-
- hide commands from the help menu
197-
- disable and re-enable commands at runtime
198+
- Remove commands included in `cmd2`
199+
- Hide commands from the help menu
200+
- Dynamically disable and re-enable commands at runtime
198201

199202
## Modular Commands and Loading/Unloading Commands
200203

201204
See [Modular Commands](./modular_commands.md) for details of how to:
202205

203-
- Define commands in separate CommandSet modules
204-
- Load or unload commands at runtime
206+
- Define commands in separate [CommandSet][cmd2.CommandSet] modules
207+
- Dynamically load or unload commands at runtime

0 commit comments

Comments
 (0)