| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
cmd2 is a tool for building interactive command line applications in Python. Its goal is to make it quick and easy for developers to build feature-rich and user-friendly interactive command line applications. It provides a simple API which is an extension of Python's built-in cmd module. cmd2 provides a wealth of features on top of cmd to make your life easier and eliminates much of the boilerplate code which would be necessary when using cmd.
Click on image below to watch a short video demonstrating the capabilities of cmd2:

The last version of cmd2 to support Python 2.7 is 0.8.9, released on August 21, 2018.
Supporting Python 2 was an increasing burden on our limited resources. Switching to support only Python 3 is allowing us to clean up the codebase, remove some cruft, and focus on developing new features.
On all operating systems, the latest stable version of cmd2 can be installed using pip:
pip install -U cmd2cmd2 works with Python 3.4+ on Windows, macOS, and Linux. It is pure Python code with few 3rd-party dependencies.
For information on other installation options, see Installation Instructions in the cmd2 documentation.
The latest documentation for cmd2 can be read online here: https://cmd2.readthedocs.io/en/latest/
It is available in HTML, PDF, and ePub formats.
Instructions for implementing each feature follow.
Extension of the cmd module. So capabilities provided by cmd still exist
import cmd2
class MyApp(cmd2.Cmd):
passclass MyApp(cmd2.Cmd):
def do_foo(self, args):
"""This docstring is the built-in help for the foo command."""
print('foo bar baz')Searchable command history
Simple scripting using ASCII text files with one command + arguments per line
Powerful and flexible built-in Python scripting of your application using the pyscript command
Parsing commands with argparse
import argparse
from cmd2 import with_argparser
argparser = argparse.ArgumentParser()
argparser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
argparser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
argparser.add_argument('words', nargs='+', help='words to say')
@with_argparser(argparser)
def do_speak(self, args):
"""Repeats what you tell me to."""
words = []
for word in args.words:
if args.piglatin:
word = '%s%say' % (word[1:], word[0])
if args.shout:
word = word.upper()
words.append(word)
self.stdout.write('{}\n'.format(' '.join(words)))See https://cmd2.readthedocs.io/en/latest/argument_processing.html for more details
NOTE: cmd2 also provides the ACArgumentParser customization of argparse.ArgumentParser for prettier formatting of help and RangeAction type
cmd2 applications function like a full-featured shell in many ways (and are cross-platform)
Top-notch tab-completion capabilities which are easy to use but very powerful
Multi-line commands
Any command accepts multi-line input when its name is listed in Cmd.multiline_commands. The program will keep expecting input until a line ends with any of the characters in Cmd.terminators . The default terminators are ; and /n (empty newline).
Special-character shortcut commands (beyond cmd's "@" and "!")
To create a single-character shortcut for a command, update Cmd.shortcuts.
Asynchronous alerts based on events happening in background threads
A few tutorials on using cmd2 exist:
Example cmd2 application (examples/example.py):
#!/usr/bin/env python
# coding=utf-8
"""
A sample application for cmd2.
"""
import argparse
import random
import cmd2
class CmdLineApp(cmd2.Cmd):
""" Example cmd2 application. """
# Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist
# default_to_shell = True
MUMBLES = ['like', '...', 'um', 'er', 'hmmm', 'ahh']
MUMBLE_FIRST = ['so', 'like', 'well']
MUMBLE_LAST = ['right?']
def __init__(self):
self.multiline_commands = ['orate']
self.maxrepeats = 3
# Add stuff to settable and shortcuts before calling base class initializer
self.settable['maxrepeats'] = 'max repetitions for speak command'
self.shortcuts.update({'&': 'speak'})
# Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell
super().__init__(use_ipython=False)
speak_parser = argparse.ArgumentParser()
speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
speak_parser.add_argument('words', nargs='+', help='words to say')
@cmd2.with_argparser(speak_parser)
def do_speak(self, args):
"""Repeats what you tell me to."""
words = []
for word in args.words:
if args.piglatin:
word = '%s%say' % (word[1:], word[0])
if args.shout:
word = word.upper()
words.append(word)
repetitions = args.repeat or 1
for i in range(min(repetitions, self.maxrepeats)):
# .poutput handles newlines, and accommodates output redirection too
self.poutput(' '.join(words))
do_say = do_speak # now "say" is a synonym for "speak"
do_orate = do_speak # another synonym, but this one takes multi-line input
mumble_parser = argparse.ArgumentParser()
mumble_parser.add_argument('-r', '--repeat', type=int, help='how many times to repeat')
mumble_parser.add_argument('words', nargs='+', help='words to say')
@cmd2.with_argparser(mumble_parser)
def do_mumble(self, args):
"""Mumbles what you tell me to."""
repetitions = args.repeat or 1
for i in range(min(repetitions, self.maxrepeats)):
output = []
if (random.random() < .33):
output.append(random.choice(self.MUMBLE_FIRST))
for word in args.words:
if (random.random() < .40):
output.append(random.choice(self.MUMBLES))
output.append(word)
if (random.random() < .25):
output.append(random.choice(self.MUMBLE_LAST))
self.poutput(' '.join(output))
if __name__ == '__main__':
c = CmdLineApp()
c.cmdloop()The following is a sample session running example.py. Thanks to Cmd2's built-in transcript testing capability, it also serves as a test suite for example.py when saved as transcript_regex.txt. Running
python example.py -t transcript_regex.txtwill run all the commands in the transcript against example.py, verifying that the output produced matches the transcript.
example/transcript_regex.txt:
# Run this transcript with "python example.py -t transcript_regex.txt"
# The regex for colors is because no color on Windows.
# The regex for editor will match whatever program you use.
# regexes on prompts just make the trailing space obvious
(Cmd) set
colors: /(True|False)/
continuation_prompt: >/ /
debug: False
echo: False
editor: /.*?/
feedback_to_output: False
locals_in_py: True
maxrepeats: 3
prompt: (Cmd)/ /
quiet: False
timing: False
Note how a regular expression /(True|False)/ is used for output of the show color command since colored text is currently not available for cmd2 on Windows. Regular expressions can be used anywhere within a transcript file simply by enclosing them within forward slashes, /.
If you think you've found a bug, please first read through the open Issues. If you're confident it's a new bug, go ahead and create a new GitHub issue. Be sure to include as much information as possible so we can reproduce the bug. At a minimum, please state the following:
Here are a few examples of open-source projects which use cmd2:
| Back | FazBrowse Home | New Git URL |