|
| 1 | +#!/usr/bin/env python |
| 2 | +# coding=utf-8 |
| 3 | +"""A simple example demonstrating the following: |
| 4 | + 1) How arguments and options get parsed and passed to commands |
| 5 | + 2) How to change what syntax get parsed as a comment and stripped from the arguments |
| 6 | +
|
| 7 | +This is intended to serve as a live demonstration so that developers can experiment with and understand how command |
| 8 | +and argument parsing is intended to work. |
| 9 | +""" |
| 10 | +import pyparsing |
| 11 | +import cmd2 |
| 12 | +from cmd2 import options, make_option |
| 13 | + |
| 14 | + |
| 15 | +class ArgumentAndOptionPrinter(cmd2.Cmd): |
| 16 | + """ Example cmd2 application where we create commands that just print the arguments they are called with.""" |
| 17 | + |
| 18 | + def __init__(self): |
| 19 | + # Uncomment this line to disable Python-style comments but still allow C-style comments |
| 20 | + # self.commentGrammars = pyparsing.Or([pyparsing.cStyleComment]) |
| 21 | + |
| 22 | + # Make sure to call this super class __init__ after setting commentGrammars and not before |
| 23 | + cmd2.Cmd.__init__(self) |
| 24 | + |
| 25 | + def do_aprint(self, arg): |
| 26 | + """Print the argument string this basic command is called with.""" |
| 27 | + print('aprint was called with argument: {!r}'.format(arg)) |
| 28 | + |
| 29 | + @options([make_option('-p', '--piglatin', action="store_true", help="atinLay"), |
| 30 | + make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE"), |
| 31 | + make_option('-r', '--repeat', type="int", help="output [n] times")], arg_desc='positional_arg_string') |
| 32 | + def do_oprint(self, arg, opts=None): |
| 33 | + """Print the options and argument list this options command was called with.""" |
| 34 | + print('oprint was called with the following\n\toptions: {!r}\n\targuments: {!r}'.format(opts, arg)) |
| 35 | + |
| 36 | + |
| 37 | +if __name__ == '__main__': |
| 38 | + app = ArgumentAndOptionPrinter() |
| 39 | + app.cmdloop() |
0 commit comments