Skip to content
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,11 @@ Instructions for implementing each feature follow.

- Searchable command history
- Readline history using `<Ctrl>+r`, arrow keys, and other [Readline Shortcut keys](http://readline.kablamo.org/emacs.html)
- Readline history can be persistent between application runs via optional argument to `cmd2.Cmd` initializer
- `cmd2` `history` command provides flexible and powerful search
- By design, this history does NOT persist between application runs
- If you wish to exclude some of your custom commands from the history, append their names to the list at `Cmd.exclude_from_history`.
- Do `help history` in any `cmd2` application for more information
- Both of the above types of history can be optionally persistent between application runs
- Via optional `persistent_history_file` argument to `cmd2.Cmd` initializer

- Simple scripting using text files with one command + arguments per line
- See the [Command Scripts](https://cmd2.readthedocs.io/en/latest/features/scripting.html#command-scripts) section of the `cmd2` docs for more info
Expand Down
24 changes: 20 additions & 4 deletions docs/features/argument_processing.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
.. _decorators:

Argument Processing
===================

Expand Down Expand Up @@ -33,19 +31,20 @@ applications.
.. _argprint: https://github.com/python-cmd2/cmd2/blob/master/examples/arg_print.py
.. _decorator: https://github.com/python-cmd2/cmd2/blob/master/examples/decorator_example.py

.. _decorators:

Decorators provided by cmd2 for argument processing
---------------------------------------------------

``cmd2`` provides the following decorators for assisting with parsing arguments
passed to commands:

.. automethod:: cmd2.decorators.with_argument_list
:noindex:
.. automethod:: cmd2.decorators.with_argparser
:noindex:
.. automethod:: cmd2.decorators.with_argparser_and_unknown_args
:noindex:
.. automethod:: cmd2.decorators.with_argument_list
:noindex:

All of these decorators accept an optional **preserve_quotes** argument which
defaults to ``False``. Setting this argument to ``True`` is useful for cases
Expand Down Expand Up @@ -342,3 +341,20 @@ use subcommands in your ``cmd2`` application.

.. _subcommands: https://github.com/python-cmd2/cmd2/blob/master/examples/subcommands.py
.. _tab_autocompletion: https://github.com/python-cmd2/cmd2/blob/master/examples/tab_autocompletion.py


Argparse Extensions
-------------------

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

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

``cmd2`` also provides the ``Cmd2ArgumentParser`` class which inherits from
``argparse.ArgumentParser`` and improves error and help output:

.. autoclass:: cmd2.argparse_custom.Cmd2ArgumentParser
:members:


47 changes: 47 additions & 0 deletions docs/features/completion.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,50 @@ similar to the following to your class which inherits from ``cmd2.Cmd``::

# Make sure you have an "import functools" somewhere at the top
complete_bar = functools.partialmethod(cmd2.Cmd.path_complete, path_filter=os.path.isdir)


Tab Completion Using Argparse Decorators
----------------------------------------

When using one the Argparse-based :ref:`decorators`, ``cmd2`` provides
automatic tab-completion of flag names.

Tab-completion of argument values can be configured by using one of five
parameters to ``argparse.ArgumentParser.add_argument()``

- ``choices``
- ``choices_function`` / ``choices_method``
- ``completer_function`` / ``completer_method``

See the arg_decorators_ or colors_ example for a demonstration of how to
use the ``choices`` parameter. See the tab_autocompletion_ example for a
demonstration of how to use the ``choices_function`` and ``choices_method``
parameters. See the arg_decorators_ or tab_autocompletion_ example for a
demonstration of how to use the ``completer_method`` parameter.

When tab-completing flags and/or argument values for a ``cmd2`` command using
one of these decorators, ``cmd2`` keeps track of state so that once a flag has
already previously been provided, it won't attempt to tab-complete it again.
When no completion results exists, a hint for the current argument will be
displayed to help the user.

.. _arg_decorators: https://github.com/python-cmd2/cmd2/blob/master/examples/arg_decorators.py
.. _colors: https://github.com/python-cmd2/cmd2/blob/master/examples/colors.py
.. _tab_autocompletion: https://github.com/python-cmd2/cmd2/blob/master/examples/tab_autocompletion..py


CompletionItem For Providing Extra Context
------------------------------------------

When tab-completing things like a unique ID from a database, it can often be
beneficial to provide the user with some extra context about the item being
completed, such as a description. To facilitate this, ``cmd2`` defines the
``CompletionItem`` class which can be returned from any of the 4 completion
functions: ``choices_function``, ``choices_method``, ``completion_function``,
or ``completion_method``.

.. autoclass:: cmd2.argparse_custom.CompletionItem
:members:

See the tab_autocompletion_ example or the implementation of the built-in
**set** command for demonstration of how this is used.
2 changes: 2 additions & 0 deletions docs/features/embedded_python_shells.rst
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,12 @@ IPython_ provides many advantages, including:
* Get help on objects with ``?``
* Extensible tab completion, with support by default for completion of
python variables and keywords
* Good built-in ipdb_ debugger

The object introspection and tab completion make IPython particularly efficient
for debugging as well as for interactive experimentation and data analysis.

.. _IPython: http://ipython.readthedocs.io
.. _ipdb: https://pypi.org/project/ipdb/


34 changes: 0 additions & 34 deletions docs/features/generating_output.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,40 +42,6 @@ messages. Users can control whether they would like to see these messages by
changing the value of the ``quiet`` setting.


Output Redirection
------------------

As in a Unix shell, output of a command can be redirected:

- sent to a file with ``>``, as in ``mycommand args > filename.txt``
- appended to a file with ``>>``, as in ``mycommand args >> filename.txt``
- piped (``|``) as input to operating-system commands, as in
``mycommand args | wc``



.. note::

If you wish to disable cmd2's output redirection and pipes features, you can
do so by setting the ``allow_redirection`` attribute of your ``cmd2.Cmd``
class instance to ``False``. This would be useful, for example, if you want
to restrict the ability for an end user to write to disk or interact with
shell commands for security reasons::

from cmd2 import Cmd
class App(Cmd):
def __init__(self):
self.allow_redirection = False

cmd2's parser will still treat the ``>``, ``>>``, and `|` symbols as output
redirection and pipe symbols and will strip arguments after them from the
command line arguments accordingly. But output from a command will not be
redirected to a file or piped to a shell command.

If you need to include any of these redirection characters in your command, you
can enclose them in quotation marks, ``mycommand 'with > in the argument'``.


Colored Output
--------------

Expand Down
1 change: 1 addition & 0 deletions docs/features/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Features
os
plugins
prompt
redirection
scripting
settings
shortcuts_aliases_macros
Expand Down
52 changes: 50 additions & 2 deletions docs/features/initialization.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,53 @@
Initialization
==============

Show how to properly initialize a ``cmd2`` app, showing parameters, sequencing,
etc.
Here is a basic example ``cmd2`` application which demonstrates many
capabilities which you may wish to utilize while initializing the app::

#!/usr/bin/env python3
# coding=utf-8
"""A simple example cmd2 appliction demonstrating the following:
1) Colorizing/stylizing output
2) Using multiline commands
3) Persistent history
4) How to run an initialization script at startup
5) How to group and categorize commands when displaying them in help
6) Opting-in to using the ipy command to run an IPython shell
7) Allowing access to your application in py and ipy
8) Displaying an intro banner upon starting your application
9) Using a custom prompt
"""
import cmd2
from cmd2 import style


class BasicApp(cmd2.Cmd):
CUSTOM_CATEGORY = 'My Custom Commands'

def __init__(self):
super().__init__(multiline_commands=['echo'], persistent_history_file='cmd2_history.dat',
startup_script='scripts/startup.txt', use_ipython=True)

self.intro = style('Welcome to cmd2!', fg='red', bg='white', bold=True)
self.prompt = 'myapp> '

# Allow access to your application in py and ipy via self
self.locals_in_py = True

# Set the default category name
self.default_category = 'cmd2 Built-in Commands'

@cmd2.with_category(CUSTOM_CATEGORY)
def do_intro(self, _):
"""Display the intro banner"""
self.poutput(self.intro)

@cmd2.with_category(CUSTOM_CATEGORY)
def do_echo(self, arg):
"""Example of a multiline command"""
self.poutput(arg)


if __name__ == '__main__':
app = BasicApp()
app.cmdloop()
49 changes: 0 additions & 49 deletions docs/features/misc.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,55 +30,6 @@ to type::
(Cmd) !ls -al


Commands At Invocation
----------------------

.. _Argparse: https://docs.python.org/3/library/argparse.html

You can send commands to your app as you invoke it by including them as extra
arguments to the program. ``cmd2`` interprets each argument as a separate
command, so you should enclose each command in quotation marks if it is more
than a one-word command.

.. code-block:: shell

$ python examples/example.py "say hello" "say Gracie" quit
hello
Gracie


.. note::

If you wish to disable cmd2's consumption of command-line arguments, you can
do so by setting the ``allow_cli_args`` argument of your ``cmd2.Cmd`` class
instance to ``False``. This would be useful, for example, if you wish to
use something like Argparse_ to parse the overall command line arguments for
your application::

from cmd2 import Cmd
class App(Cmd):
def __init__(self):
super().__init__(allow_cli_args=False)


Initialization Script
---------------------

.. _AliasStartup: https://github.com/python-cmd2/cmd2/blob/master/examples/alias_startup.py

You can execute commands from an initialization script by passing a file
path to the ``startup_script`` argument to the ``cmd2.Cmd.__init__()`` method
like so::

class StartupApp(cmd2.Cmd):
def __init__(self):
cmd2.Cmd.__init__(self, startup_script='.cmd2rc')

This text file should contain a :ref:`Command Script
<features/scripting:Command Scripts>`. See the AliasStartup_ example for a
demonstration.


select
------

Expand Down
Loading