Skip to content

Commit 6895dea

Browse files
authored
Merge pull request #248 from python-cmd2/argparse_bugfixes
Argparse bugfix
2 parents 0a03ab8 + 3607a39 commit 6895dea

File tree

5 files changed

+126
-67
lines changed

5 files changed

+126
-67
lines changed

README.md

Lines changed: 78 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -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%say' % (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

113123
Tutorials
@@ -126,45 +136,80 @@ Example Application
126136
Example 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

133151
class 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%say' % (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%say' % (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

169214
if __name__ == '__main__':
170215
c = CmdLineApp()
@@ -207,4 +252,4 @@ timing: False
207252

208253
Note how a regular expression `/(True|False)/` is used for output of the **show color** command since
209254
colored 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, `/`.

cmd2.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -248,17 +248,17 @@ def with_argument_parser(argparser):
248248
argparse.ArgumentParser.
249249
"""
250250
def arg_decorator(func):
251-
def cmd_wrapper(instance, arg):
251+
def cmd_wrapper(instance, cmdline):
252252
# Use shlex to split the command line into a list of arguments based on shell rules
253-
lexed_arglist = shlex.split(arg, posix=POSIX_SHLEX)
253+
lexed_arglist = shlex.split(cmdline, posix=POSIX_SHLEX)
254254
# If not using POSIX shlex, make sure to strip off outer quotes for convenience
255255
if not POSIX_SHLEX and STRIP_QUOTES_FOR_NON_POSIX:
256256
temp_arglist = []
257257
for arg in lexed_arglist:
258258
temp_arglist.append(strip_quotes(arg))
259259
lexed_arglist = temp_arglist
260260
opts = argparser.parse_args(lexed_arglist)
261-
func(instance, arg, opts)
261+
func(instance, cmdline, opts)
262262

263263
# argparser defaults the program name to sys.argv[0]
264264
# we want it to be the name of our command

examples/argparse_example.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,13 @@ def __init__(self, ip_addr=None, port=None, transcript_files=None):
4141
# self.default_to_shell = True
4242

4343

44-
argparser = argparse.ArgumentParser(prog='speak')
44+
argparser = argparse.ArgumentParser()
4545
argparser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
4646
argparser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
4747
argparser.add_argument('-r', '--repeat', type=int, help='output [n] times')
4848
argparser.add_argument('words', nargs='+', help='words to say')
4949
@with_argument_parser(argparser)
50-
def do_speak(self, argv, args=None):
50+
def do_speak(self, cmdline, args=None):
5151
"""Repeats what you tell me to."""
5252
words = []
5353
for word in args.words:
@@ -58,10 +58,7 @@ def do_speak(self, argv, args=None):
5858
words.append(word)
5959
repetitions = args.repeat or 1
6060
for i in range(min(repetitions, self.maxrepeats)):
61-
self.stdout.write(' '.join(words))
62-
self.stdout.write('\n')
63-
# self.stdout.write is better than "print", because Cmd can be
64-
# initialized with a non-standard output destination
61+
self.poutput(' '.join(words))
6562

6663
do_say = do_speak # now "say" is a synonym for "speak"
6764
do_orate = do_speak # another synonym, but this one takes multi-line input

examples/example.py

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@
1212
"""
1313

1414
import random
15+
import argparse
1516

16-
from cmd2 import Cmd, make_option, options, set_use_arg_list
17+
from cmd2 import Cmd, with_argument_parser
1718

1819

1920
class CmdLineApp(Cmd):
@@ -37,41 +38,41 @@ def __init__(self):
3738
# Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell
3839
Cmd.__init__(self, use_ipython=False)
3940

40-
# For option commands, pass a single argument string instead of a list of argument strings to the do_* methods
41-
set_use_arg_list(False)
42-
43-
opts = [make_option('-p', '--piglatin', action="store_true", help="atinLay"),
44-
make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE"),
45-
make_option('-r', '--repeat', type="int", help="output [n] times")]
46-
47-
@options(opts, arg_desc='(text to say)')
48-
def do_speak(self, arg, opts=None):
41+
argparser = argparse.ArgumentParser()
42+
argparser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
43+
argparser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
44+
argparser.add_argument('-r', '--repeat', type=int, help='output [n] times')
45+
argparser.add_argument('words', nargs='+', help='words to say')
46+
@with_argument_parser(argparser)
47+
def do_speak(self, cmdline, opts=None):
4948
"""Repeats what you tell me to."""
50-
arg = ''.join(arg)
51-
if opts.piglatin:
52-
arg = '%s%say' % (arg[1:], arg[0])
53-
if opts.shout:
54-
arg = arg.upper()
55-
repetitions = opts.repeat or 1
49+
words = []
50+
for word in args.words:
51+
if args.piglatin:
52+
word = '%s%say' % (word[1:], word[0])
53+
if args.shout:
54+
word = word.upper()
55+
words.append(word)
56+
repetitions = args.repeat or 1
5657
for i in range(min(repetitions, self.maxrepeats)):
57-
self.poutput(arg)
58-
# recommend using the poutput function instead of
59-
# self.stdout.write or "print", because Cmd allows the user
60-
# to redirect output
58+
# .poutput handles newlines, and accommodates output redirection too
59+
self.poutput(' '.join(words))
6160

6261
do_say = do_speak # now "say" is a synonym for "speak"
6362
do_orate = do_speak # another synonym, but this one takes multi-line input
6463

65-
@options([ make_option('-r', '--repeat', type="int", help="output [n] times") ])
66-
def do_mumble(self, arg, opts=None):
64+
argparser = argparse.ArgumentParser()
65+
argparser.add_argument('-r', '--repeat', type=int, help='how many times to repeat')
66+
argparser.add_argument('words', nargs='+', help='words to say')
67+
@with_argument_parser(argparser)
68+
def do_mumble(self, cmdline, args=None):
6769
"""Mumbles what you tell me to."""
68-
repetitions = opts.repeat or 1
69-
arg = arg.split()
70+
repetitions = args.repeat or 1
7071
for i in range(min(repetitions, self.maxrepeats)):
7172
output = []
7273
if (random.random() < .33):
7374
output.append(random.choice(self.MUMBLE_FIRST))
74-
for word in arg:
75+
for word in args.words:
7576
if (random.random() < .40):
7677
output.append(random.choice(self.MUMBLES))
7778
output.append(word)

tests/test_argparse.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"""
33
Cmd2 testing for argument parsing
44
"""
5+
import re
56
import argparse
67
import pytest
78

@@ -43,6 +44,16 @@ def do_tag(self, cmdline, args=None):
4344
self.stdout.write('<{0}>{1}</{0}>'.format(args.tag[0], ' '.join(args.content)))
4445
self.stdout.write('\n')
4546

47+
argparser = argparse.ArgumentParser()
48+
argparser.add_argument('args', nargs='*')
49+
@cmd2.with_argument_parser(argparser)
50+
def do_compare(self, cmdline, args=None):
51+
cmdline_str = re.sub('\s+', ' ', cmdline)
52+
args_str = re.sub('\s+', ' ', ' '.join(args.args))
53+
if cmdline_str == args_str:
54+
self.stdout.write('True')
55+
else:
56+
self.stdout.write('False')
4657

4758
@pytest.fixture
4859
def argparse_app():
@@ -88,4 +99,9 @@ def test_argparse_prog(argparse_app):
8899
out = run_cmd(argparse_app, 'help tag')
89100
progname = out[0].split(' ')[1]
90101
assert progname == 'tag'
102+
103+
def test_argparse_cmdline(argparse_app):
104+
out = run_cmd(argparse_app, 'compare this is a test')
105+
assert out[0] == 'True'
106+
91107

0 commit comments

Comments
 (0)