@@ -29,7 +29,7 @@ Main Features
2929- Multi-line, case-insensitive, and abbreviated commands
3030- Special-character command shortcuts (beyond cmd's ` @ ` and ` ! ` )
3131- Settable environment parameters
32- - Parsing commands with flags
32+ - Parsing commands with arguments using ` argparse `
3333- Unicode character support (* Python 3 only* )
3434- Good tab-completion of commands, file system paths, and shell commands
3535- Python 2.7 and 3.4+ support
@@ -97,17 +97,27 @@ Instructions for implementing each feature follow.
9797 To allow a user to change an environment parameter during program execution,
9898 append the parameter's name to `Cmd.settable``
9999
100- - Parsing commands with ` optparse ` options (flags)
100+ - Parsing commands with ` argparse `
101101
102102 ``` python
103- @options ([make_option(' -m' , ' --myoption' , action = " store_true" , help = " all about my option" )])
104- def do_myfunc (self , arg , opts ):
105- if opts.myoption:
106- # TODO : Do something useful
107- pass
103+ argparser = argparse.ArgumentParser()
104+ argparser.add_argument(' -p' , ' --piglatin' , action = ' store_true' , help = ' atinLay' )
105+ argparser.add_argument(' -s' , ' --shout' , action = ' store_true' , help = ' N00B EMULATION MODE' )
106+ argparser.add_argument(' words' , nargs = ' +' , help = ' words to say' )
107+ @with_argument_parser (argparser)
108+ def do_speak (self , cmdline , args = None ):
109+ """ Repeats what you tell me to."""
110+ words = []
111+ for word in args.words:
112+ if args.piglatin:
113+ word = ' %s%s ay' % (word[1 :], word[0 ])
114+ if args.shout:
115+ word = word.upper()
116+ words.append(word)
117+ self .stdout.write(' {} \n ' .format(' ' .join(words)))
108118 ```
109119
110- See Python standard library ' s `optparse` documentation: https://docs.python.org/3/library/optparse .html
120+ See https:// cmd2.readthedocs.io / en / latest / argument_processing .html for more details
111121
112122
113123Tutorials
@@ -126,45 +136,80 @@ Example Application
126136Example cmd2 application (** examples/ example.py** ):
127137
128138```python
129- ''' A sample application for cmd2.'''
139+ # !/usr/bin/env python
140+ # coding=utf-8
141+ """
142+ A sample application for cmd2.
143+ """
144+
145+ import random
146+ import argparse
147+
148+ from cmd2 import Cmd, with_argument_parser
130149
131- from cmd2 import Cmd, make_option, options, set_use_arg_list
132150
133151class CmdLineApp(Cmd):
152+ """ Example cmd2 application. """
153+
154+ # Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist
155+ # default_to_shell = True
156+ MUMBLES = [' like' , ' ...' , ' um' , ' er' , ' hmmm' , ' ahh' ]
157+ MUMBLE_FIRST = [' so' , ' like' , ' well' ]
158+ MUMBLE_LAST = [' right?' ]
159+
134160 def __init__ (self ):
161+ self .abbrev = True
135162 self .multilineCommands = [' orate' ]
136163 self .maxrepeats = 3
137164
138- # Add stuff to settable and shortcutgs before calling base class initializer
165+ # Add stuff to settable and shortcuts before calling base class initializer
139166 self .settable[' maxrepeats' ] = ' max repetitions for speak command'
140167 self .shortcuts.update({' &' : ' speak' })
141168
142169 # Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell
143170 Cmd.__init__ (self , use_ipython = False )
144171
145- # For option commands, pass a single argument string instead of a list of argument strings to the do_* methods
146- set_use_arg_list(False )
147-
148- @options ([make_option(' -p' , ' --piglatin' , action = " store_true" , help = " atinLay" ),
149- make_option(' -s' , ' --shout' , action = " store_true" , help = " N00B EMULATION MODE" ),
150- make_option(' -r' , ' --repeat' , type = " int" , help = " output [n] times" )
151- ])
152- def do_speak (self , arg , opts = None ):
172+ argparser = argparse.ArgumentParser()
173+ argparser.add_argument(' -p' , ' --piglatin' , action = ' store_true' , help = ' atinLay' )
174+ argparser.add_argument(' -s' , ' --shout' , action = ' store_true' , help = ' N00B EMULATION MODE' )
175+ argparser.add_argument(' -r' , ' --repeat' , type = int , help = ' output [n] times' )
176+ argparser.add_argument(' words' , nargs = ' +' , help = ' words to say' )
177+ @ with_argument_parser(argparser)
178+ def do_speak(self , cmdline, opts = None ):
153179 """ Repeats what you tell me to."""
154- arg = ' ' .join(arg)
155- if opts.piglatin:
156- arg = ' %s%s ay' % (arg[1 :], arg[0 ])
157- if opts.shout:
158- arg = arg.upper()
159- repetitions = opts.repeat or 1
180+ words = []
181+ for word in args.words:
182+ if args.piglatin:
183+ word = ' %s%s ay' % (word[1 :], word[0 ])
184+ if args.shout:
185+ word = word.upper()
186+ words.append(word)
187+ repetitions = args.repeat or 1
160188 for i in range (min (repetitions, self .maxrepeats)):
161- self .stdout.write(arg)
162- self .stdout.write(' \n ' )
163- # self.stdout.write is better than "print", because Cmd can be
164- # initialized with a non-standard output destination
165-
166- do_say = do_speak # now "say" is a synonym for "speak"
167- do_orate = do_speak # another synonym, but this one takes multi-line input
189+ # .poutput handles newlines, and accommodates output redirection too
190+ self .poutput(' ' .join(words))
191+
192+ do_say = do_speak # now "say" is a synonym for "speak"
193+ do_orate = do_speak # another synonym, but this one takes multi-line input
194+
195+ argparser = argparse.ArgumentParser()
196+ argparser.add_argument(' -r' , ' --repeat' , type = int , help = ' how many times to repeat' )
197+ argparser.add_argument(' words' , nargs = ' +' , help = ' words to say' )
198+ @ with_argument_parser(argparser)
199+ def do_mumble(self , cmdline, args = None ):
200+ """ Mumbles what you tell me to."""
201+ repetitions = args.repeat or 1
202+ for i in range (min (repetitions, self .maxrepeats)):
203+ output = []
204+ if (random.random() < .33 ):
205+ output.append(random.choice(self .MUMBLE_FIRST ))
206+ for word in args.words:
207+ if (random.random() < .40 ):
208+ output.append(random.choice(self .MUMBLES ))
209+ output.append(word)
210+ if (random.random() < .25 ):
211+ output.append(random.choice(self .MUMBLE_LAST ))
212+ self .poutput(' ' .join(output))
168213
169214if __name__ == ' __main__' :
170215 c = CmdLineApp()
@@ -207,4 +252,4 @@ timing: False
207252
208253Note how a regular expression `/ (True | False )/ ` is used for output of the ** show color** command since
209254colored text is currently not available for cmd2 on Windows. Regular expressions can be used anywhere within a
210- transcript file simply by embedding them within two forward slashes, ` / ` .
255+ transcript file simply by enclosing them within forward slashes, `/ ` .
0 commit comments