summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rwxr-xr-xexamples/arg_print.py4
-rwxr-xr-xexamples/argparse_example.py6
-rwxr-xr-xexamples/example.py6
-rwxr-xr-xexamples/pirate.py20
-rwxr-xr-xexamples/subcommands.py61
-rw-r--r--examples/transcripts/exampleSession.txt (renamed from examples/exampleSession.txt)0
-rw-r--r--examples/transcripts/pirate.transcript10
-rw-r--r--examples/transcripts/transcript_regex.txt (renamed from examples/transcript_regex.txt)0
8 files changed, 89 insertions, 18 deletions
diff --git a/examples/arg_print.py b/examples/arg_print.py
index 1b18cdf0..8b02bc51 100755
--- a/examples/arg_print.py
+++ b/examples/arg_print.py
@@ -14,7 +14,7 @@ import argparse
import cmd2
import pyparsing
-from cmd2 import with_argument_list, with_argument_parser, with_argparser_and_unknown_args
+from cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args
class ArgumentAndOptionPrinter(cmd2.Cmd):
@@ -47,7 +47,7 @@ class ArgumentAndOptionPrinter(cmd2.Cmd):
oprint_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
oprint_parser.add_argument('words', nargs='+', help='words to print')
- @with_argument_parser(oprint_parser)
+ @with_argparser(oprint_parser)
def do_oprint(self, args):
"""Print the options and argument list this options command was called with."""
print('oprint was called with the following\n\toptions: {!r}'.format(args))
diff --git a/examples/argparse_example.py b/examples/argparse_example.py
index 9f6548de..fbb2b1dc 100755
--- a/examples/argparse_example.py
+++ b/examples/argparse_example.py
@@ -14,7 +14,7 @@ verifying that the output produced matches the transcript.
import argparse
import sys
-from cmd2 import Cmd, options, with_argument_parser, with_argument_list
+from cmd2 import Cmd, options, with_argparser, with_argument_list
from optparse import make_option
@@ -47,7 +47,7 @@ class CmdLineApp(Cmd):
speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
speak_parser.add_argument('words', nargs='+', help='words to say')
- @with_argument_parser(speak_parser)
+ @with_argparser(speak_parser)
def do_speak(self, args):
"""Repeats what you tell me to."""
words = []
@@ -68,7 +68,7 @@ class CmdLineApp(Cmd):
tag_parser.add_argument('tag', help='tag')
tag_parser.add_argument('content', nargs='+', help='content to surround with tag')
- @with_argument_parser(tag_parser)
+ @with_argparser(tag_parser)
def do_tag(self, args):
"""create a html tag"""
self.poutput('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content)))
diff --git a/examples/example.py b/examples/example.py
index 4ba0d29a..c66f0e60 100755
--- a/examples/example.py
+++ b/examples/example.py
@@ -14,7 +14,7 @@ the transcript.
import random
import argparse
-from cmd2 import Cmd, with_argument_parser
+from cmd2 import Cmd, with_argparser
class CmdLineApp(Cmd):
@@ -44,7 +44,7 @@ class CmdLineApp(Cmd):
speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
speak_parser.add_argument('words', nargs='+', help='words to say')
- @with_argument_parser(speak_parser)
+ @with_argparser(speak_parser)
def do_speak(self, args):
"""Repeats what you tell me to."""
words = []
@@ -66,7 +66,7 @@ class CmdLineApp(Cmd):
mumble_parser.add_argument('-r', '--repeat', type=int, help='how many times to repeat')
mumble_parser.add_argument('words', nargs='+', help='words to say')
- @with_argument_parser(mumble_parser)
+ @with_argparser(mumble_parser)
def do_mumble(self, args):
"""Mumbles what you tell me to."""
repetitions = args.repeat or 1
diff --git a/examples/pirate.py b/examples/pirate.py
index dd9fd98c..cfe545d6 100755
--- a/examples/pirate.py
+++ b/examples/pirate.py
@@ -7,7 +7,7 @@ presented as part of her PyCon 2010 talk.
It demonstrates many features of cmd2.
"""
import argparse
-from cmd2 import Cmd, with_argument_parser
+from cmd2 import Cmd, with_argparser
class Pirate(Cmd):
@@ -25,13 +25,13 @@ class Pirate(Cmd):
"""Initialize the base class as well as this one"""
Cmd.__init__(self)
# prompts and defaults
- self.gold = 3
+ self.gold = 0
self.initial_gold = self.gold
self.prompt = 'arrr> '
def default(self, line):
"""This handles unknown commands."""
- print('What mean ye by "{0}"?'.format(line))
+ self.poutput('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."""
@@ -41,10 +41,10 @@ class Pirate(Cmd):
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'
+ self.poutput('Now we gots {0} doubloons'
.format(self.gold))
if self.gold < 0:
- print("Off to debtorrr's prison.")
+ self.poutput("Off to debtorrr's prison.")
stop = True
return stop
@@ -61,30 +61,30 @@ class Pirate(Cmd):
self.gold -= int(arg)
except ValueError:
if arg:
- print('''What's "{0}"? I'll take rrrum.'''.format(arg))
+ self.poutput('''What's "{0}"? I'll take rrrum.'''.format(arg))
self.gold -= 1
def do_quit(self, arg):
"""Quit the application gracefully."""
- print("Quiterrr!")
+ self.poutput("Quiterrr!")
return True
def do_sing(self, arg):
"""Sing a colorful song."""
- print(self.colorize(arg, self.songcolor))
+ self.poutput(self.colorize(arg, self.songcolor))
yo_parser = argparse.ArgumentParser()
yo_parser.add_argument('--ho', type=int, default=2, help="How often to chant 'ho'")
yo_parser.add_argument('-c', '--commas', action='store_true', help='Intersperse commas')
yo_parser.add_argument('beverage', help='beverage to drink with the chant')
- @with_argument_parser(yo_parser)
+ @with_argparser(yo_parser)
def do_yo(self, args):
"""Compose a yo-ho-ho type chant with flexible options."""
chant = ['yo'] + ['ho'] * args.ho
separator = ', ' if args.commas else ' '
chant = separator.join(chant)
- print('{0} and a bottle of {1}'.format(chant, args.beverage))
+ self.poutput('{0} and a bottle of {1}'.format(chant, args.beverage))
if __name__ == '__main__':
diff --git a/examples/subcommands.py b/examples/subcommands.py
new file mode 100755
index 00000000..e77abc61
--- /dev/null
+++ b/examples/subcommands.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+# coding=utf-8
+"""A simple example demonstrating how to use Argparse to support sub-commands.
+
+
+This example shows an easy way for a single command to have many subcommands, each of which takes different arguments
+and provides separate contextual help.
+"""
+import argparse
+
+import cmd2
+from cmd2 import with_argparser
+
+
+class SubcommandsExample(cmd2.Cmd):
+ """ Example cmd2 application where we a base command which has a couple subcommands."""
+
+ def __init__(self):
+ cmd2.Cmd.__init__(self)
+
+ # sub-command functions for the base command
+ def base_foo(self, args):
+ """foo subcommand of base command"""
+ self.poutput(args.x * args.y)
+
+ def base_bar(self, args):
+ """bar sucommand of base command"""
+ self.poutput('((%s))' % args.z)
+
+ # create the top-level parser for the base command
+ base_parser = argparse.ArgumentParser(prog='base')
+ base_subparsers = base_parser.add_subparsers(title='subcommands', help='subcommand help')
+
+ # create the parser for the "foo" sub-command
+ parser_foo = base_subparsers.add_parser('foo', help='foo help')
+ parser_foo.add_argument('-x', type=int, default=1, help='integer')
+ parser_foo.add_argument('y', type=float, help='float')
+ parser_foo.set_defaults(func=base_foo)
+
+ # create the parser for the "bar" sub-command
+ parser_bar = base_subparsers.add_parser('bar', help='bar help')
+ parser_bar.add_argument('z', help='string')
+ parser_bar.set_defaults(func=base_bar)
+
+ # Create a list of subcommand names, which is used to enable tab-completion of sub-commands
+ subcommands = ['foo', 'bar']
+
+ @with_argparser(base_parser, subcommands)
+ def do_base(self, args):
+ """Base command help"""
+ try:
+ # Call whatever sub-command function was selected
+ args.func(self, args)
+ except AttributeError:
+ # No sub-command was provided, so as called
+ self.do_help('base')
+
+
+if __name__ == '__main__':
+ app = SubcommandsExample()
+ app.cmdloop()
diff --git a/examples/exampleSession.txt b/examples/transcripts/exampleSession.txt
index 840bee60..840bee60 100644
--- a/examples/exampleSession.txt
+++ b/examples/transcripts/exampleSession.txt
diff --git a/examples/transcripts/pirate.transcript b/examples/transcripts/pirate.transcript
new file mode 100644
index 00000000..570f0cd7
--- /dev/null
+++ b/examples/transcripts/pirate.transcript
@@ -0,0 +1,10 @@
+arrr> loot
+Now we gots 1 doubloons
+arrr> loot
+Now we gots 2 doubloons
+arrr> loot
+Now we gots 3 doubloons
+arrr> drink 3
+Now we gots 0 doubloons
+arrr> yo --ho 3 rum
+yo ho ho ho and a bottle of rum
diff --git a/examples/transcript_regex.txt b/examples/transcripts/transcript_regex.txt
index 7d017dee..7d017dee 100644
--- a/examples/transcript_regex.txt
+++ b/examples/transcripts/transcript_regex.txt