summaryrefslogtreecommitdiff
path: root/examples/argparse_example.py
diff options
context:
space:
mode:
Diffstat (limited to 'examples/argparse_example.py')
-rwxr-xr-xexamples/argparse_example.py84
1 files changed, 66 insertions, 18 deletions
diff --git a/examples/argparse_example.py b/examples/argparse_example.py
index 6fc2b15b..fbb2b1dc 100755
--- a/examples/argparse_example.py
+++ b/examples/argparse_example.py
@@ -1,19 +1,21 @@
#!/usr/bin/env python
# coding=utf-8
-"""A sample application for cmd2 showing how to use Argparse to process command line arguments for your application.
-It parses command line arguments looking for known arguments, but then still passes any unknown arguments onto cmd2
-to treat them as arguments at invocation.
+"""A sample application for cmd2 showing how to use argparse to
+process command line arguments for your application.
-Thanks to cmd2's built-in transcript testing capability, it also serves as a test suite for argparse_example.py when
-used with the exampleSession.txt transcript.
+Thanks to cmd2's built-in transcript testing capability, it also
+serves as a test suite for argparse_example.py when used with the
+exampleSession.txt transcript.
-Running `python argparse_example.py -t exampleSession.txt` will run all the commands in the transcript against
-argparse_example.py, verifying that the output produced matches the transcript.
+Running `python argparse_example.py -t exampleSession.txt` will run
+all the commands in the transcript against argparse_example.py,
+verifying that the output produced matches the transcript.
"""
import argparse
import sys
-from cmd2 import Cmd, make_option, options
+from cmd2 import Cmd, options, with_argparser, with_argument_list
+from optparse import make_option
class CmdLineApp(Cmd):
@@ -39,27 +41,73 @@ class CmdLineApp(Cmd):
# Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist
# self.default_to_shell = True
+ 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')
+
+ @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)):
+ 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
+
+ tag_parser = argparse.ArgumentParser()
+ tag_parser.add_argument('tag', help='tag')
+ tag_parser.add_argument('content', nargs='+', help='content to surround with tag')
+
+ @with_argparser(tag_parser)
+ def do_tag(self, args):
+ """create a html tag"""
+ self.poutput('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content)))
+
+
+ @with_argument_list
+ def do_tagg(self, arglist):
+ """verion of creating an html tag using arglist instead of argparser"""
+ if len(arglist) >= 2:
+ tag = arglist[0]
+ content = arglist[1:]
+ self.poutput('<{0}>{1}</{0}>'.format(tag, ' '.join(content)))
+ else:
+ self.perror("tagg requires at least 2 arguments")
+
+
+ # @options uses the python optparse module which has been deprecated
+ # since 2011. Use @with_argument_parser instead, which utilizes the
+ # python argparse module
@options([make_option('-p', '--piglatin', action="store_true", help="atinLay"),
make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE"),
make_option('-r', '--repeat', type="int", help="output [n] times")
])
- def do_speak(self, arg, opts=None):
+ def do_deprecated_speak(self, arg, opts=None):
"""Repeats what you tell me to."""
- arg = ''.join(arg)
- if opts.piglatin:
- arg = '%s%say' % (arg[1:], arg[0])
- if opts.shout:
- arg = arg.upper()
+ words = []
+ for word in arg:
+ if opts.piglatin:
+ word = '%s%say' % (word[1:], word[0])
+ if opts.shout:
+ arg = arg.upper()
+ words.append(word)
repetitions = opts.repeat or 1
for i in range(min(repetitions, self.maxrepeats)):
- self.stdout.write(arg)
+ self.stdout.write(' '.join(words))
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
-
if __name__ == '__main__':
# You can do your custom Argparse parsing here to meet your application's needs