Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions examples/pirate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#!/usr/bin/env python
# coding=utf-8
"""
This example is adapted from the pirate8.py example created by Catherine Devlin and
presented as part of her PyCon 2010 talk.

It demonstrates many features of cmd2.
"""
from cmd2 import Cmd, options, make_option


class Pirate(Cmd):
"""A piratical example cmd2 application involving looting and drinking."""
default_to_shell = True
multilineCommands = ['sing']
terminators = Cmd.terminators + ['...']
songcolor = 'blue'
settable = Cmd.settable + 'songcolor Color to ``sing`` in (red/blue/green/cyan/magenta, bold, underline)'
Cmd.shortcuts.update({'~': 'sing'})

def __init__(self):
"""Initialize the base class as well as this one"""
Cmd.__init__(self)
# prompts and defaults
self.gold = 3
self.initial_gold = self.gold
self.prompt = 'arrr> '

def default(self, line):
"""This handles unknown commands."""
print('What mean ye by "{0}"?'.format(line))

def precmd(self, line):
"""Runs just before a command line is parsed, but after the prompt is presented."""
self.initial_gold = self.gold
return line

def postcmd(self, stop, line):
"""Runs right before a command is about to return."""
if self.gold != self.initial_gold:
print('Now we gots {0} doubloons'
.format(self.gold))
if self.gold < 0:
print("Off to debtorrr's prison.")
stop = True
return stop

# noinspection PyUnusedLocal
def do_loot(self, arg):
"""Seize booty from a passing ship."""
self.gold += 1

def do_drink(self, arg):
"""Drown your sorrrows in rrrum.

drink [n] - drink [n] barrel[s] o' rum."""
try:
self.gold -= int(arg)
except ValueError:
if arg:
print('''What's "{0}"? I'll take rrrum.'''.format(arg))
self.gold -= 1

def do_quit(self, arg):
"""Quit the applicaiton gracefully."""
print("Quiterrr!")
return True

def do_sing(self, arg):
"""Sing a colorful song."""
print(self.colorize(arg, self.songcolor))

@options([make_option('--ho', type='int', default=2,
help="How often to chant 'ho'"),
make_option('-c', '--commas',
action="store_true",
help="Intersperse commas")])
def do_yo(self, arg, opts):
"""Compose a yo-ho-ho type chant with flexible options."""
chant = ['yo'] + ['ho'] * opts.ho
separator = ', ' if opts.commas else ' '
chant = separator.join(chant)
print('{0} and a bottle of {1}'.format(chant, arg))


if __name__ == '__main__':
# Create an instance of the Pirate derived class and enter the REPL with cmdlooop().
pirate = Pirate()
pirate.cmdloop()
26 changes: 23 additions & 3 deletions examples/python_scripting.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,23 @@ class CmdLineApp(Cmd):
""" Example cmd2 application to showcase conditional control flow in Python scripting within cmd2 aps. """

def __init__(self):
Cmd.__init__(self)
# Enable the optional ipy command if IPython is installed by setting use_ipython=True
Cmd.__init__(self, use_ipython=True)
self._set_prompt()

def _set_prompt(self):
"""Set prompt so it displays the current working directory."""
self.prompt = '{!r} $ '.format(os.getcwd())
self.cwd = os.getcwd()
self.subdirs = [d for d in os.listdir(self.cwd) if os.path.isdir(d)]
self.prompt = '{!r} $ '.format(self.cwd)

def postcmd(self, stop, line):
"""Hook method executed just after a command dispatch is finished.

:param stop: bool - if True, the command has indicated the application should exit
:param line: str - the command line text for this command
:return: bool - if this is True, the application will exit after this command and the postloop() will run
"""
"""Override this so prompt always displays cwd."""
self._set_prompt()
return stop
Expand Down Expand Up @@ -73,6 +82,17 @@ def do_cd(self, arg, opts=None):
self.perror(err, traceback_war=False)
self._last_result = CmdResult(out, err, war)

def complete_cd(self, text, line, begidx, endidx):
"""Handles completion of arguments for the cd command.

:param text: str - the string prefix we are attempting to match (all returned matches must begin with it)
:param line: str - the current input line with leading whitespace removed
:param begidx: str - the beginning indexe of the prefix text
:param endidx: str - the ending index of the prefix text
:return: List[str] - a list of possible tab completions
"""
return [d for d in self.subdirs if d.startswith(text)]

@options([make_option('-l', '--long', action="store_true", help="display in long format with one item per line")],
arg_desc='')
def do_dir(self, arg, opts=None):
Expand All @@ -85,7 +105,7 @@ def do_dir(self, arg, opts=None):
return

# Get the contents as a list
contents = os.listdir(os.getcwd())
contents = os.listdir(self.cwd)

fmt = '{} '
if opts.long:
Expand Down