From 57ce8cc24a44a035ae1830ba6e7d5faf9f4bf95f Mon Sep 17 00:00:00 2001 From: Todd Leonhardt Date: Sat, 4 Mar 2017 18:44:00 -0500 Subject: Added info to CHANGES.rst on what bugs have been fixed so far this release. Fixed a bug where the allow_cli_args attribute wasn't properly preventing OptParse from prasing the args looking for "-t" or "--test" for transcript testing. Added an example of using Argparse with cmd2. --- examples/argparse_example.py | 88 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100755 examples/argparse_example.py (limited to 'examples/argparse_example.py') diff --git a/examples/argparse_example.py b/examples/argparse_example.py new file mode 100755 index 00000000..8f833578 --- /dev/null +++ b/examples/argparse_example.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# coding=utf-8 +"""A sample application for cmd2 showing how to use Argparse to process command line arguments for your application. +It doubles as an example of how you can still do transcript testing even if allow_cli_args is false. + +Thanks to cmd2's built-in transtript testing capability, it also serves as a test suite for argparse_example.py when +used with the exampleSession.txt transcript. + +Running `python argparse_example.py -t exampleSession.txt` will run all the commands in the transcript against +argparse_example.py, verifying that the output produced matches the transcript. +""" +import argparse + +from cmd2 import Cmd, make_option, options + + +class CmdLineApp(Cmd): + """ Example cmd2 application. """ + multilineCommands = ['orate'] + Cmd.shortcuts.update({'&': 'speak'}) + maxrepeats = 3 + Cmd.settable.append('maxrepeats') + + # Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist + # default_to_shell = True + + def __init__(self, ip_addr=None, port=None, transcript_files=None): + # Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell + Cmd.__init__(self, use_ipython=False, transcript_files=transcript_files) + + # Disable cmd's usage of command-line arguments as commands to be run at invocation + self.allow_cli_args = False + + # Example of args set from the command-line (but they aren't being used here) + self._ip = ip_addr + self._port = port + + @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") + ]) + def do_speak(self, arg, opts=None): + """Repeats what you tell me to.""" + arg = ''.join(arg) + if opts.piglatin: + arg = '%s%say' % (arg[1:], arg[0]) + if opts.shout: + arg = arg.upper() + repetitions = opts.repeat or 1 + for i in range(min(repetitions, self.maxrepeats)): + self.stdout.write(arg) + self.stdout.write('\n') + # self.stdout.write is better than "print", because Cmd can be + # initialized with a non-standard output destination + + do_say = do_speak # now "say" is a synonym for "speak" + do_orate = do_speak # another synonym, but this one takes multi-line input + + +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.') + + # Add a few arguments which aren't really used, but just to get the gist + parser.add_argument('-p', '--port', type=int, help='TCP port') + parser.add_argument('-i', '--ip', type=str, help='IPv4 address') + + # Add an argument which enables transcript testing + parser.add_argument('-t', '--test', type=str, help='Test against transcript in FILE (wildcards OK)') + args = parser.parse_args() + + port = None + if args.port: + port = args.port + + ip_addr = None + if args.ip: + ip_addr = args.ip + + transcript = None + if args.test: + transcripts = [args.test] + + # Instantiate your cmd2 applicaiton + c = CmdLineApp(transcript_files=transcripts) + + # And run your cmd2 application + c.cmdloop() -- cgit v1.2.1