summaryrefslogtreecommitdiff
path: root/examples/argparse_example.py
diff options
context:
space:
mode:
authorJared Crapo <jared@kotfu.net>2017-12-11 19:14:09 -0700
committerJared Crapo <jared@kotfu.net>2017-12-11 19:14:09 -0700
commit4f57dc14a7ffc2cbd741622da7d05d42ba7f7789 (patch)
treea7342e6981d44b9b19b9852c3f0e822aa702f659 /examples/argparse_example.py
parentb16b91268ecbea934e96a68b7feb2965f4ab3c18 (diff)
downloadcmd2-git-4f57dc14a7ffc2cbd741622da7d05d42ba7f7789.tar.gz
Plan and first working code for argparse decorator
Diffstat (limited to 'examples/argparse_example.py')
-rwxr-xr-xexamples/argparse_example.py26
1 files changed, 25 insertions, 1 deletions
diff --git a/examples/argparse_example.py b/examples/argparse_example.py
index 1358559c..8c25b0ef 100755
--- a/examples/argparse_example.py
+++ b/examples/argparse_example.py
@@ -11,7 +11,7 @@ argparse_example.py, verifying that the output produced matches the transcript.
"""
import argparse
-from cmd2 import Cmd, make_option, options
+from cmd2 import Cmd, make_option, options, with_argument_parser
class CmdLineApp(Cmd):
@@ -55,6 +55,30 @@ class CmdLineApp(Cmd):
# self.stdout.write is better than "print", because Cmd can be
# initialized with a non-standard output destination
+ argparser = argparse.ArgumentParser(
+ prog='sspeak',
+ description='Repeats what you tell me to'
+ )
+ 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('-r', '--repeat', type=int, help='output [n] times')
+ argparser.add_argument('word', nargs='?', help='word to say')
+ @with_argument_parser(argparser)
+ def do_sspeak(self, rawarg, args=None):
+ """Repeats what you tell me to."""
+ word = args.word
+ if word is None:
+ word = ''
+ if args.piglatin:
+ word = '%s%say' % (word[1:], word[0])
+ if args.shout:
+ word = word.upper()
+ repetitions = args.repeat or 1
+ for i in range(min(repetitions, self.maxrepeats)):
+ self.stdout.write(word)
+ self.stdout.write('\n')
+ # self.stdout.write is better than "print", because Cmd can be
+ # initialized with a non-standard output destination
do_say = do_speak # now "say" is a synonym for "speak"
do_orate = do_speak # another synonym, but this one takes multi-line input