Skip to content

Commit 65cf54a

Browse files
committed
command documentation for #765
1 parent d6549c8 commit 65cf54a

File tree

1 file changed

+158
-22
lines changed

1 file changed

+158
-22
lines changed

docs/features/commands.rst

Lines changed: 158 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,45 +3,181 @@ Commands
33

44
.. _cmd: https://docs.python.org/3/library/cmd.html
55

6-
How to create a command with a ``do_command`` method,
6+
``cmd2`` is designed to make it easy for you to create new commands. These
7+
commmands form the backbone of your application. If you started writing your
8+
application using cmd_, all the commands you have built will work when you move
9+
to ``cmd2``. However, there are many more capabilities available in ``cmd2``
10+
which you can take advantage of to add more robust features to your commands,
11+
and which makes your commands easier to write. Before we get to all the good
12+
stuff, let's briefly discuss how to create a new command in your application.
713

8-
Parsed statements
9-
-----------------
1014

11-
``cmd2`` passes ``arg`` to a ``do_`` method (or ``default``) as a Statement, a
12-
subclass of string that includes many attributes of the parsed input:
15+
Basic Commands
16+
--------------
17+
18+
The simplest ``cmd2`` application looks like this::
19+
20+
#!/usr/bin/env python
21+
"""A simple cmd2 application."""
22+
import cmd2
23+
24+
25+
class App(cmd2.Cmd):
26+
"""A simple cmd2 application."""
27+
28+
29+
if __name__ == '__main__':
30+
import sys
31+
c = App()
32+
sys.exit(c.cmdloop())
33+
34+
This application subclasses ``cmd2.Cmd`` but has no code of it's own, so all
35+
functionality (and there's quite a bit) is inherited. Lets create a simple
36+
command in this application called ``echo`` which outputs any arguments given
37+
to it. Add this method to the class::
38+
39+
def do_echo(self, line):
40+
self.poutput(line)
41+
42+
When you type input into the ``cmd2`` prompt, the first space delimited word is
43+
treated as the command name. ``cmd2`` looks for a method called
44+
``do_commandname``. If it exists, it calls the method, passing the rest of the
45+
user input as the first argument. If it doesn't exist ``cmd2`` prints an error
46+
message. As a result of this behavior, the only thing you have to do to create
47+
a new command is to define a new method in the class with the appropriate name.
48+
This is exactly how you would create a command using the cmd_ module which is
49+
part of the python standard library.
50+
51+
.. note::
52+
53+
See :ref:`features/generating_output:Generating Output` if you are
54+
unfamiliar with the ``poutput()`` method.
55+
56+
57+
Statements
58+
----------
59+
60+
A command is passed one argument: a string which contains all the rest of the
61+
user input. However, in ``cmd2`` this string is actually a ``Statement``
62+
object, which is a subclass of ``str`` to retain backwards compatibility.
63+
64+
``cmd2`` has a much more sophsticated parsing engine than what's included in
65+
the cmd_ module. This parsing handles:
66+
67+
- quoted arguments
68+
- output redirection and piping
69+
- multi-line commands
70+
- shortcut, macro, and alias expansion
71+
72+
In addition to parsing all of these elements from the user input, ``cmd2`` also
73+
has code to make all of these items work; it's almost transparent to you and to
74+
the commands you write in your own application. However, by passing your
75+
command the ``Statement`` object instead of just a plain string, you can get
76+
visibility into what ``cmd2`` has done with the user input before your command
77+
got it. You can also avoid writing a bunch of parsing code, because ``cmd2``
78+
gives you access to what it has already parsed.
79+
80+
A ``Statement`` object is a subclass of ``str`` that contains the following
81+
attributes:
1382

1483
command
15-
Name of the command called
84+
Name of the command called. You already know this because of the method
85+
``cmd2`` called, but it can sometimes be nice to have it in a string, i.e.
86+
if you want your error messages to contain the command name.
1687

1788
args
18-
The arguments to the command with output redirection
19-
or piping to shell commands removed
89+
A string containing the arguments to the command with output redirection or
90+
piping to shell commands removed. It turns out that the "string" value of
91+
the ``Statement`` object has all the output redirection and piping clauses
92+
removed as well. Quotes remain in the string.
2093

2194
command_and_args
22-
A string of just the command and the arguments, with
23-
output redirection or piping to shell commands removed
95+
A string of just the command and the arguments, with output redirection or
96+
piping to shell commands removed.
2497

2598
argv
26-
A list of arguments a-la ``sys.argv``, including
27-
the command as ``argv[0]`` and the subsequent
28-
arguments as additional items in the list.
29-
Quotes around arguments will be stripped as will
30-
any output redirection or piping portions of the command
99+
A list of arguments a-la ``sys.argv``, including the command as ``argv[0]``
100+
and the subsequent arguments as additional items in the list. Quotes around
101+
arguments will be stripped as will any output redirection or piping
102+
portions of the command.
31103

32104
raw
33-
Full input exactly as typed.
105+
Full input exactly as typed by the user.
34106

35107
terminator
36-
Character used to end a multiline command
108+
Character used to end a multiline command. You can configure multiple
109+
termination characters, and this attribute will tell you which one the user
110+
typed.
111+
112+
For many simple commands, like the ``echo`` command above, you can ignore the
113+
``Statement`` object and all of it's attributes and just use the passed value
114+
as a string. You might choose to use the ``argv`` attribute to do more
115+
sophisticated argument processing. Before you go to far down that path, you
116+
should check out the :ref:`features/argument_processing:Argument Processing`
117+
functionality included with ``cmd2``.
118+
119+
120+
Return Values
121+
-------------
122+
123+
Most commands should return nothing (either my omitting a ``return`` statement,
124+
or by ``return None``. This indicates that your command is finished (with or
125+
without errors), and that ``cmd2`` should prompt the user for more input.
126+
127+
If you return ``True`` from a command method, that indicates to ``cmd2`` that
128+
it should stop prompting for user input and cleanly exit. ``cmd2`` already
129+
includes a ``quit`` command, but if you wanted to make another one called
130+
``finis`` you could::
131+
132+
def do_finis(self, line):
133+
"""Exit the application"""
134+
return True
135+
136+
137+
Exit Codes
138+
----------
139+
140+
``cmd2`` has basic infrastructure to support sh/ksh/csh/bash type exit codes.
141+
The ``cmd2.Cmd`` object sets an ``exit_code`` attribute to zero when it is
142+
instantiated. The value of this attribute is returned from the ``cmdloop()``
143+
call, so if you want to get an exit code back to the operating system shell,
144+
you can do so like this::
145+
146+
#!/usr/bin/env python
147+
"""A simple cmd2 application."""
148+
import cmd2
149+
150+
151+
class App(cmd2.Cmd):
152+
"""A simple cmd2 application."""
153+
154+
def do_bail(self, line):
155+
"""Exit the application""
156+
self.poutput("fatal error, exiting")
157+
self.exit_code = 2
158+
return true
37159

160+
if __name__ == '__main__':
161+
import sys
162+
c = App()
163+
sys.exit(c.cmdloop())
38164

165+
If the app was run from the `bash` operating system shell, then you would see
166+
the following interaction::
39167

40-
If ``Statement`` does not contain an attribute, querying for it will return
41-
``None``.
168+
(Cmd) bail
169+
fatal error, exiting
170+
$ echo $?
171+
2
42172

43-
(Getting ``arg`` as a ``Statement`` is technically "free", in that it requires
44-
no application changes from the cmd_ standard, but there will be no result
45-
unless you change your application to *use* any of the additional attributes.)
46173

174+
Exception Handling
175+
------------------
47176

177+
You may choose you may choose to catch and handle any exceptions which occur in
178+
a command method. If the command method raises an exception, ``cmd2`` will
179+
catch it and display it for you. The `debug` :ref:`setting
180+
<features/settings:Settings>` controls how the exception is displayed. If
181+
`debug` is `false`, which is the default, ``cmd2`` will display the exception
182+
name and message. If `debug` is `true`, ``cmd2`` will display a traceback, and
183+
then display the exception name and message.

0 commit comments

Comments
 (0)