From 4f57dc14a7ffc2cbd741622da7d05d42ba7f7789 Mon Sep 17 00:00:00 2001 From: Jared Crapo Date: Mon, 11 Dec 2017 19:14:09 -0700 Subject: Plan and first working code for argparse decorator --- examples/argparse_example.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) (limited to 'examples/argparse_example.py') 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 -- cgit v1.2.1