diff options
author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2018-01-15 01:34:50 -0500 |
---|---|---|
committer | Todd Leonhardt <todd.leonhardt@gmail.com> | 2018-01-15 01:34:50 -0500 |
commit | 141d95194b30d959f6c21f4546100551c442b13d (patch) | |
tree | 5d1602a6d2117aaa4910adfff31ad919b85fea07 | |
parent | 2fcc883f8a7fd5c9fd3beb30465cfa2b86c66ffc (diff) | |
download | cmd2-git-141d95194b30d959f6c21f4546100551c442b13d.tar.gz |
Made a couple cleanup changes
1) cmd2 no longer imports make_option from optparse
- test files and examples now import this directly
- this helps emphasize that this old optparse methodology of adding options to commands is deprecated
2) All argparsers have been given custom names instead of just "argparser"
- this helps with readability and maintainability, especially with IDE renaming and such
-rwxr-xr-x | cmd2.py | 23 | ||||
-rwxr-xr-x | examples/argparse_example.py | 24 | ||||
-rwxr-xr-x | examples/example.py | 29 | ||||
-rw-r--r-- | tests/test_argparse.py | 42 | ||||
-rw-r--r-- | tests/test_cmd2.py | 5 | ||||
-rw-r--r-- | tests/test_transcript.py | 7 |
6 files changed, 70 insertions, 60 deletions
@@ -42,7 +42,6 @@ import tempfile import traceback import unittest from code import InteractiveConsole -from optparse import make_option import pyparsing import pyperclip @@ -1172,7 +1171,6 @@ class Cmd(cmd.Cmd): return stop - # noinspection PyUnusedLocal def do_cmdenvironment(self, _): """Summary report of interactive parameters.""" self.poutput(""" @@ -1239,13 +1237,11 @@ class Cmd(cmd.Cmd): self.print_topics(self.misc_header, list(help_dict.keys()), 15, 80) self.print_topics(self.undoc_header, cmds_undoc, 15, 80) - # noinspection PyUnusedLocal def do_shortcuts(self, _): """Lists shortcuts (aliases) available.""" result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts)) self.poutput("Shortcuts for other commands:\n{}\n".format(result)) - # noinspection PyUnusedLocal def do_eof(self, _): """Called when <Ctrl>-D is pressed.""" # End of script should not exit app, but <Ctrl>-D should. @@ -1292,10 +1288,11 @@ class Cmd(cmd.Cmd): len(fulloptions))) return result - argparser = argparse.ArgumentParser(description='show value of a parameter') - argparser.add_argument('-l', '--long', action='store_true', help='describe function of parameter') - argparser.add_argument('param', nargs='?', help='name of parameter, if not supplied show all parameters') - @with_argument_parser(argparser) + show_parser = argparse.ArgumentParser(description='show value of a parameter') + show_parser.add_argument('-l', '--long', action='store_true', help='describe function of parameter') + show_parser.add_argument('param', nargs='?', help='name of parameter, if not supplied show all parameters') + + @with_argument_parser(show_parser) def do_show(self, arglist, args): param = '' if args.param: @@ -1616,6 +1613,8 @@ class Cmd(cmd.Cmd): def do_pyscript(self, arglist): """\nRuns a python script file inside the console + Usage: pyscript <script_path> [script_arguments] + Console commands can be executed inside this script with cmd("your command") However, you cannot run nested "py" or "pyscript" commands from within this script Paths or arguments that contain spaces must be enclosed in quotes @@ -1657,19 +1656,19 @@ Paths or arguments that contain spaces must be enclosed in quotes exit_msg = 'Leaving IPython, back to {}'.format(sys.argv[0]) embed(banner1=banner, exit_msg=exit_msg) - argparser = argparse.ArgumentParser( + show_parser = argparse.ArgumentParser( description='list past commands issued', formatter_class=argparse.RawTextHelpFormatter, ) - argparser.add_argument('-s', '--script', action='store_true', help='script format; no separation lines') + show_parser.add_argument('-s', '--script', action='store_true', help='script format; no separation lines') _history_arg_help = """no arg list all arg is integer by index a..b, a:b, a:, ..b by indices (inclusive) arg is string containing string arg is /regex/ matching regular expression regex""" - argparser.add_argument('arg', nargs='*', help=_history_arg_help) + show_parser.add_argument('arg', nargs='*', help=_history_arg_help) - @with_argument_parser(argparser) + @with_argument_parser(show_parser) def do_history(self, arglist, args): # If an argument was supplied, then retrieve partial contents of the history if args.arg: diff --git a/examples/argparse_example.py b/examples/argparse_example.py index 40ea372c..b203feef 100755 --- a/examples/argparse_example.py +++ b/examples/argparse_example.py @@ -14,7 +14,8 @@ verifying that the output produced matches the transcript. import argparse import sys -from cmd2 import Cmd, make_option, options, with_argument_parser, with_argument_list +from cmd2 import Cmd, options, with_argument_parser, with_argument_list +from optparse import make_option class CmdLineApp(Cmd): @@ -40,13 +41,13 @@ 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') - argparser = argparse.ArgumentParser() - 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('words', nargs='+', help='words to say') - @with_argument_parser(argparser) + @with_argument_parser(speak_parser) def do_speak(self, arglist, args=None): """Repeats what you tell me to.""" words = [] @@ -63,11 +64,11 @@ class CmdLineApp(Cmd): 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(description='create a html tag') + tag_parser.add_argument('tag', nargs=1, help='tag') + tag_parser.add_argument('content', nargs='+', help='content to surround with tag') - argparser = argparse.ArgumentParser(description='create a html tag') - argparser.add_argument('tag', nargs=1, help='tag') - argparser.add_argument('content', nargs='+', help='content to surround with tag') - @with_argument_parser(argparser) + @with_argument_parser(tag_parser) def do_tag(self, arglist, args=None): """create a html tag""" self.poutput('<{0}>{1}</{0}>'.format(args.tag[0], ' '.join(args.content))) @@ -107,6 +108,7 @@ class CmdLineApp(Cmd): # self.stdout.write is better than "print", because Cmd can be # initialized with a non-standard output destination + if __name__ == '__main__': # You can do your custom Argparse parsing here to meet your application's needs parser = argparse.ArgumentParser(description='Process the arguments however you like.') diff --git a/examples/example.py b/examples/example.py index d7d4e21c..7c78edc3 100755 --- a/examples/example.py +++ b/examples/example.py @@ -38,12 +38,13 @@ class CmdLineApp(Cmd): # Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell Cmd.__init__(self, use_ipython=False) - argparser = argparse.ArgumentParser() - 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('words', nargs='+', help='words to say') - @with_argument_parser(argparser) + 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_argument_parser(speak_parser) def do_speak(self, cmdline, opts=None): """Repeats what you tell me to.""" words = [] @@ -61,25 +62,27 @@ class CmdLineApp(Cmd): do_say = do_speak # now "say" is a synonym for "speak" do_orate = do_speak # another synonym, but this one takes multi-line input - argparser = argparse.ArgumentParser() - argparser.add_argument('-r', '--repeat', type=int, help='how many times to repeat') - argparser.add_argument('words', nargs='+', help='words to say') - @with_argument_parser(argparser) + mumble_parser = argparse.ArgumentParser() + mumble_parser.add_argument('-r', '--repeat', type=int, help='how many times to repeat') + mumble_parser.add_argument('words', nargs='+', help='words to say') + + @with_argument_parser(mumble_parser) def do_mumble(self, cmdline, args=None): """Mumbles what you tell me to.""" repetitions = args.repeat or 1 for i in range(min(repetitions, self.maxrepeats)): output = [] - if (random.random() < .33): + if random.random() < .33: output.append(random.choice(self.MUMBLE_FIRST)) for word in args.words: - if (random.random() < .40): + if random.random() < .40: output.append(random.choice(self.MUMBLES)) output.append(word) - if (random.random() < .25): + if random.random() < .25: output.append(random.choice(self.MUMBLE_LAST)) self.poutput(' '.join(output)) + if __name__ == '__main__': c = CmdLineApp() c.cmdloop() diff --git a/tests/test_argparse.py b/tests/test_argparse.py index cfe0ec5c..0222af30 100644 --- a/tests/test_argparse.py +++ b/tests/test_argparse.py @@ -14,12 +14,13 @@ class ArgparseApp(cmd2.Cmd): self.maxrepeats = 3 cmd2.Cmd.__init__(self) - argparser = argparse.ArgumentParser() - 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('words', nargs='+', help='words to say') - @cmd2.with_argument_parser(argparser) + say_parser = argparse.ArgumentParser() + say_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay') + say_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE') + say_parser.add_argument('-r', '--repeat', type=int, help='output [n] times') + say_parser.add_argument('words', nargs='+', help='words to say') + + @cmd2.with_argument_parser(say_parser) def do_say(self, arglist, args=None): """Repeat what you tell me to.""" words = [] @@ -36,17 +37,19 @@ class ArgparseApp(cmd2.Cmd): self.stdout.write(' '.join(words)) self.stdout.write('\n') - argparser = argparse.ArgumentParser(description='create a html tag') - argparser.add_argument('tag', nargs=1, help='tag') - argparser.add_argument('content', nargs='+', help='content to surround with tag') - @cmd2.with_argument_parser(argparser) + tag_parser = argparse.ArgumentParser(description='create a html tag') + tag_parser.add_argument('tag', nargs=1, help='tag') + tag_parser.add_argument('content', nargs='+', help='content to surround with tag') + + @cmd2.with_argument_parser(tag_parser) def do_tag(self, arglist, args=None): self.stdout.write('<{0}>{1}</{0}>'.format(args.tag[0], ' '.join(args.content))) self.stdout.write('\n') - argparser = argparse.ArgumentParser() - argparser.add_argument('args', nargs='*') - @cmd2.with_argument_parser(argparser) + compare_parser = argparse.ArgumentParser() + compare_parser.add_argument('args', nargs='*') + + @cmd2.with_argument_parser(compare_parser) def do_compare(self, arglist, args=None): cmdline_str = re.sub('\s+', ' ', ' '.join(arglist)) args_str = re.sub('\s+', ' ', ' '.join(args.args)) @@ -55,9 +58,10 @@ class ArgparseApp(cmd2.Cmd): else: self.stdout.write('False') - argparser = argparse.ArgumentParser() - argparser.add_argument('args', nargs='*') - @cmd2.with_argument_parser(argparser) + argpasre_arglist_parser = argparse.ArgumentParser() + argpasre_arglist_parser.add_argument('args', nargs='*') + + @cmd2.with_argument_parser(argpasre_arglist_parser) def do_argparse_arglist(self, arglist, args=None): if isinstance(arglist, list): self.stdout.write('True') @@ -65,10 +69,10 @@ class ArgparseApp(cmd2.Cmd): self.stdout.write('False') - argparser = argparse.ArgumentParser() - argparser.add_argument('args', nargs='*') + arglist_and_argparser_parser = argparse.ArgumentParser() + arglist_and_argparser_parser.add_argument('args', nargs='*') @cmd2.with_argument_list - @cmd2.with_argument_parser(argparser) + @cmd2.with_argument_parser(arglist_and_argparser_parser) def do_arglistandargparser(self, arglist, args=None): if isinstance(arglist, list): self.stdout.write(' '.join(arglist)) diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index 156b9a73..3fc7c4ea 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -15,6 +15,7 @@ import pytest import six from code import InteractiveConsole +from optparse import make_option # Used for sm.input: raw_input() for Python 2 or input() for Python 3 import six.moves as sm @@ -1273,7 +1274,7 @@ arg 2: 'bar' class OptionApp(cmd2.Cmd): - @cmd2.options([cmd2.make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE")]) + @cmd2.options([make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE")]) def do_greet(self, arg, opts=None): arg = ''.join(arg) if opts.shout: @@ -1316,7 +1317,7 @@ class MultilineApp(cmd2.Cmd): # Need to use this older form of invoking super class constructor to support Python 2.x and Python 3.x cmd2.Cmd.__init__(self, *args, **kwargs) - @cmd2.options([cmd2.make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE")]) + @cmd2.options([make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE")]) def do_orate(self, arg, opts=None): arg = ''.join(arg) if opts.shout: diff --git a/tests/test_transcript.py b/tests/test_transcript.py index e572e919..0daad18a 100644 --- a/tests/test_transcript.py +++ b/tests/test_transcript.py @@ -17,9 +17,10 @@ import six # Used for sm.input: raw_input() for Python 2 or input() for Python 3 import six.moves as sm -from cmd2 import (Cmd, make_option, options, Cmd2TestCase, set_use_arg_list, +from cmd2 import (Cmd, options, Cmd2TestCase, set_use_arg_list, set_posix_shlex, set_strip_quotes) from conftest import run_cmd, StdOut, normalize +from optparse import make_option class CmdLineApp(Cmd): @@ -27,7 +28,7 @@ class CmdLineApp(Cmd): MUMBLES = ['like', '...', 'um', 'er', 'hmmm', 'ahh'] MUMBLE_FIRST = ['so', 'like', 'well'] MUMBLE_LAST = ['right?'] - + def __init__(self, *args, **kwargs): self.abbrev = True self.multilineCommands = ['orate'] @@ -332,7 +333,7 @@ def test_transcript(request, capsys, filename, feedback_to_output): ]) def test_parse_transcript_expected(expected, transformed): app = CmdLineApp() - + class TestMyAppCase(Cmd2TestCase): cmdapp = app |