summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorTodd Leonhardt <todd.leonhardt@gmail.com>2018-01-15 12:11:12 -0500
committerTodd Leonhardt <todd.leonhardt@gmail.com>2018-01-15 12:11:12 -0500
commiteee2d621abfb3d6455570b540069a4853a68f8c6 (patch)
tree6bfc049369079868eab6f05ce8d0cae233c43cb9 /examples
parentaec6704db9542e35e4cdc6073210bc0d6c507335 (diff)
downloadcmd2-git-eee2d621abfb3d6455570b540069a4853a68f8c6.tar.gz
Changed @with_argument_parser to only pass single argument to commands
Also added another @with_argparser_and_list decorator that uses argparse.parse_known_args to pass two arguments to a command: both the argparse output and a list of unknown/unmatched args.
Diffstat (limited to 'examples')
-rwxr-xr-xexamples/arg_print.py39
-rwxr-xr-xexamples/argparse_example.py4
-rwxr-xr-xexamples/example.py4
-rwxr-xr-xexamples/pirate.py23
-rwxr-xr-xexamples/python_scripting.py18
5 files changed, 56 insertions, 32 deletions
diff --git a/examples/arg_print.py b/examples/arg_print.py
index 00507649..f5ec2a51 100755
--- a/examples/arg_print.py
+++ b/examples/arg_print.py
@@ -9,10 +9,12 @@ and argument parsing is intended to work.
It also serves as an example of how to create command aliases (shortcuts).
"""
-import pyparsing
+import argparse
+
import cmd2
-from cmd2 import options
-from optparse import make_option
+import pyparsing
+
+from cmd2 import with_argument_list, with_argument_parser, with_argparser_and_list
class ArgumentAndOptionPrinter(cmd2.Cmd):
@@ -23,7 +25,7 @@ class ArgumentAndOptionPrinter(cmd2.Cmd):
# self.commentGrammars = pyparsing.Or([pyparsing.cStyleComment])
# Create command aliases which are shorter
- self.shortcuts.update({'ap': 'aprint', 'op': 'oprint'})
+ self.shortcuts.update({'$': 'aprint', '%': 'oprint'})
# Make sure to call this super class __init__ *after* setting commentGrammars and/or updating shortcuts
cmd2.Cmd.__init__(self)
@@ -34,12 +36,31 @@ class ArgumentAndOptionPrinter(cmd2.Cmd):
"""Print the argument string this basic command is called with."""
print('aprint was called with argument: {!r}'.format(arg))
- @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")], arg_desc='positional_arg_string')
- def do_oprint(self, arg, opts=None):
+ @with_argument_list
+ def do_lprint(self, arglist):
+ """Print the argument list this basic command is called with."""
+ print('lprint was called with the following list of arguments: {!r}'.format(arglist))
+
+ oprint_parser = argparse.ArgumentParser()
+ oprint_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
+ oprint_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
+ oprint_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
+ oprint_parser.add_argument('words', nargs='+', help='words to print')
+
+ @with_argument_parser(oprint_parser)
+ def do_oprint(self, args):
+ """Print the options and argument list this options command was called with."""
+ print('oprint was called with the following\n\toptions: {!r}'.format(args))
+
+ pprint_parser = argparse.ArgumentParser()
+ pprint_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
+ pprint_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
+ pprint_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
+ @with_argparser_and_list(pprint_parser)
+ def do_pprint(self, args, unknown):
"""Print the options and argument list this options command was called with."""
- print('oprint was called with the following\n\toptions: {!r}\n\targuments: {!r}'.format(opts, arg))
+ print('oprint was called with the following\n\toptions: {!r}\n\targuments: {}'.format(args, unknown))
+
if __name__ == '__main__':
diff --git a/examples/argparse_example.py b/examples/argparse_example.py
index b203feef..ae45411c 100755
--- a/examples/argparse_example.py
+++ b/examples/argparse_example.py
@@ -48,7 +48,7 @@ class CmdLineApp(Cmd):
speak_parser.add_argument('words', nargs='+', help='words to say')
@with_argument_parser(speak_parser)
- def do_speak(self, arglist, args=None):
+ def do_speak(self, args):
"""Repeats what you tell me to."""
words = []
for word in args.words:
@@ -69,7 +69,7 @@ class CmdLineApp(Cmd):
tag_parser.add_argument('content', nargs='+', help='content to surround with tag')
@with_argument_parser(tag_parser)
- def do_tag(self, arglist, args=None):
+ def do_tag(self, args):
"""create a html tag"""
self.poutput('<{0}>{1}</{0}>'.format(args.tag[0], ' '.join(args.content)))
diff --git a/examples/example.py b/examples/example.py
index 7c78edc3..4ba0d29a 100755
--- a/examples/example.py
+++ b/examples/example.py
@@ -45,7 +45,7 @@ class CmdLineApp(Cmd):
speak_parser.add_argument('words', nargs='+', help='words to say')
@with_argument_parser(speak_parser)
- def do_speak(self, cmdline, opts=None):
+ def do_speak(self, args):
"""Repeats what you tell me to."""
words = []
for word in args.words:
@@ -67,7 +67,7 @@ class CmdLineApp(Cmd):
mumble_parser.add_argument('words', nargs='+', help='words to say')
@with_argument_parser(mumble_parser)
- def do_mumble(self, cmdline, args=None):
+ def do_mumble(self, args):
"""Mumbles what you tell me to."""
repetitions = args.repeat or 1
for i in range(min(repetitions, self.maxrepeats)):
diff --git a/examples/pirate.py b/examples/pirate.py
index f8c91315..55457e06 100755
--- a/examples/pirate.py
+++ b/examples/pirate.py
@@ -6,8 +6,8 @@ presented as part of her PyCon 2010 talk.
It demonstrates many features of cmd2.
"""
-from cmd2 import Cmd, options
-from optparse import make_option
+import argparse
+from cmd2 import Cmd, with_argument_parser
class Pirate(Cmd):
@@ -73,17 +73,18 @@ class Pirate(Cmd):
"""Sing a colorful song."""
print(self.colorize(arg, self.songcolor))
- @options([make_option('--ho', type='int', default=2,
- help="How often to chant 'ho'"),
- make_option('-c', '--commas',
- action="store_true",
- help="Intersperse commas")])
- def do_yo(self, arg, opts):
+ yo_parser = argparse.ArgumentParser()
+ yo_parser.add_argument('--ho', type=int, default=2, help="How often to chant 'ho'")
+ yo_parser.add_argument('-c', '--commas', action='store_true', help='Intersperse commas')
+ yo_parser.add_argument('beverage', nargs=1, help='beverage to drink with the chant')
+
+ @with_argument_parser(yo_parser)
+ def do_yo(self, args):
"""Compose a yo-ho-ho type chant with flexible options."""
- chant = ['yo'] + ['ho'] * opts.ho
- separator = ', ' if opts.commas else ' '
+ chant = ['yo'] + ['ho'] * args.ho
+ separator = ', ' if args.commas else ' '
chant = separator.join(chant)
- print('{0} and a bottle of {1}'.format(chant, arg))
+ print('{0} and a bottle of {1}'.format(chant, args.beverage[0]))
if __name__ == '__main__':
diff --git a/examples/python_scripting.py b/examples/python_scripting.py
index 68290a7b..a2892dc8 100755
--- a/examples/python_scripting.py
+++ b/examples/python_scripting.py
@@ -14,11 +14,11 @@ command and the "pyscript <script> [arguments]" syntax comes into play.
This application and the "scripts/conditional.py" script serve as an example for one way in which this can be done.
"""
+import argparse
import functools
import os
-from cmd2 import Cmd, options, CmdResult, with_argument_list
-from optparse import make_option
+from cmd2 import Cmd, CmdResult, with_argument_list, with_argparser_and_list
class CmdLineApp(Cmd):
@@ -86,13 +86,15 @@ class CmdLineApp(Cmd):
# Enable directory completion for cd command by freezing an argument to path_complete() with functools.partialmethod
complete_cd = functools.partialmethod(Cmd.path_complete, dir_only=True)
- @options([make_option('-l', '--long', action="store_true", help="display in long format with one item per line")],
- arg_desc='')
- def do_dir(self, arg, opts=None):
+ dir_parser = argparse.ArgumentParser()
+ dir_parser.add_argument('-l', '--long', action='store_true', help="display in long format with one item per line")
+
+ @with_argparser_and_list(dir_parser)
+ def do_dir(self, args, unknown):
"""List contents of current directory."""
# No arguments for this command
- if arg:
- self.perror("dir does not take any arguments:", traceback_war=False)
+ if unknown:
+ self.perror("dir does not take any positional arguments:", traceback_war=False)
self.do_help('dir')
self._last_result = CmdResult('', 'Bad arguments')
return
@@ -101,7 +103,7 @@ class CmdLineApp(Cmd):
contents = os.listdir(self.cwd)
fmt = '{} '
- if opts.long:
+ if args.long:
fmt = '{}\n'
for f in contents:
self.stdout.write(fmt.format(f))