summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorTodd Leonhardt <todd.leonhardt@gmail.com>2018-01-17 09:28:43 -0500
committerGitHub <noreply@github.com>2018-01-17 09:28:43 -0500
commit91bc999d022a486334b9054859e2ef6f03ca9666 (patch)
treed71c32f3b47c2b137d6b9543a605feb8380472a7 /examples
parent6895dea2e19210093e38fa411ef28dfb7f99c32c (diff)
parent1da904585db4cd1e77c312190149daa946366fa0 (diff)
downloadcmd2-git-91bc999d022a486334b9054859e2ef6f03ca9666.tar.gz
Merge pull request #249 from python-cmd2/arglist
decorator changes for replacing optparse with argparse
Diffstat (limited to 'examples')
-rwxr-xr-xexamples/arg_print.py38
-rwxr-xr-xexamples/argparse_example.py46
-rwxr-xr-xexamples/example.py33
-rw-r--r--examples/exampleSession.txt1
-rwxr-xr-xexamples/pirate.py22
-rwxr-xr-xexamples/python_scripting.py35
-rw-r--r--examples/transcript_regex.txt1
7 files changed, 107 insertions, 69 deletions
diff --git a/examples/arg_print.py b/examples/arg_print.py
index 849cf386..1b18cdf0 100755
--- a/examples/arg_print.py
+++ b/examples/arg_print.py
@@ -9,9 +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, make_option
+import pyparsing
+
+from cmd2 import with_argument_list, with_argument_parser, with_argparser_and_unknown_args
class ArgumentAndOptionPrinter(cmd2.Cmd):
@@ -22,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)
@@ -33,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_unknown_args(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 d784ccf5..ae45411c 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
+from cmd2 import Cmd, options, with_argument_parser, with_argument_list
+from optparse import make_option
class CmdLineApp(Cmd):
@@ -40,14 +41,14 @@ 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)
- def do_speak(self, cmdline, args=None):
+ @with_argument_parser(speak_parser)
+ def do_speak(self, args):
"""Repeats what you tell me to."""
words = []
for word in args.words:
@@ -63,16 +64,26 @@ 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')
+
+ @with_argument_parser(tag_parser)
+ def do_tag(self, args):
+ """create a html tag"""
+ self.poutput('<{0}>{1}</{0}>'.format(args.tag[0], ' '.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")
- 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)
- def do_tag(self, argv, args=None):
- self.stdout.write('<{0}>{1}</{0}>'.format(args.tag[0], ' '.join(args.content)))
- self.stdout.write('\n')
- # self.stdout.write is better than "print", because Cmd can be
- # initialized with a non-standard output destination
# @options uses the python optparse module which has been deprecated
# since 2011. Use @with_argument_parser instead, which utilizes the
@@ -97,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..4ba0d29a 100755
--- a/examples/example.py
+++ b/examples/example.py
@@ -38,13 +38,14 @@ 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)
- def do_speak(self, cmdline, opts=None):
+ 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, args):
"""Repeats what you tell me to."""
words = []
for word in args.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)
- def do_mumble(self, cmdline, args=None):
+ 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, args):
"""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/examples/exampleSession.txt b/examples/exampleSession.txt
index ef6df857..840bee60 100644
--- a/examples/exampleSession.txt
+++ b/examples/exampleSession.txt
@@ -4,7 +4,6 @@
# regexes on prompts just make the trailing space obvious
(Cmd) set
abbrev: False
-autorun_on_edit: False
colors: /(True|False)/
continuation_prompt: >/ /
debug: False
diff --git a/examples/pirate.py b/examples/pirate.py
index 32d7769e..55457e06 100755
--- a/examples/pirate.py
+++ b/examples/pirate.py
@@ -6,7 +6,8 @@ presented as part of her PyCon 2010 talk.
It demonstrates many features of cmd2.
"""
-from cmd2 import Cmd, options, make_option
+import argparse
+from cmd2 import Cmd, with_argument_parser
class Pirate(Cmd):
@@ -72,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 ae04fda1..aa62007a 100755
--- a/examples/python_scripting.py
+++ b/examples/python_scripting.py
@@ -14,10 +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, make_option, CmdResult, set_use_arg_list
+from cmd2 import Cmd, CmdResult, with_argument_list, with_argparser_and_unknown_args
class CmdLineApp(Cmd):
@@ -27,12 +28,8 @@ class CmdLineApp(Cmd):
# Enable the optional ipy command if IPython is installed by setting use_ipython=True
Cmd.__init__(self, use_ipython=True)
self._set_prompt()
- self.autorun_on_edit = False
self.intro = 'Happy 𝛑 Day. Note the full Unicode support: 😇 (Python 3 only) 💩'
- # For option commands, pass a list of argument strings instead of a single argument string to the do_* methods
- set_use_arg_list(True)
-
def _set_prompt(self):
"""Set prompt so it displays the current working directory."""
self.cwd = os.getcwd()
@@ -49,19 +46,21 @@ class CmdLineApp(Cmd):
self._set_prompt()
return stop
- # noinspection PyUnusedLocal
- @options([], arg_desc='<new_dir>')
- def do_cd(self, arg, opts=None):
- """Change directory."""
+ @with_argument_list
+ def do_cd(self, arglist):
+ """Change directory.
+ Usage:
+ cd <new_dir>
+ """
# Expect 1 argument, the directory to change to
- if not arg or len(arg) != 1:
+ if not arglist or len(arglist) != 1:
self.perror("cd requires exactly 1 argument:", traceback_war=False)
self.do_help('cd')
self._last_result = CmdResult('', 'Bad arguments')
return
# Convert relative paths to absolute paths
- path = os.path.abspath(os.path.expanduser(arg[0]))
+ path = os.path.abspath(os.path.expanduser(arglist[0]))
# Make sure the directory exists, is a directory, and we have read access
out = ''
@@ -86,13 +85,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_unknown_args(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 +102,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))
diff --git a/examples/transcript_regex.txt b/examples/transcript_regex.txt
index 27b4c639..7d017dee 100644
--- a/examples/transcript_regex.txt
+++ b/examples/transcript_regex.txt
@@ -4,7 +4,6 @@
# regexes on prompts just make the trailing space obvious
(Cmd) set
abbrev: True
-autorun_on_edit: False
colors: /(True|False)/
continuation_prompt: >/ /
debug: False