|
| 1 | +#!/usr/bin/env python |
| 2 | +# coding=utf-8 |
| 3 | +"""A simple example demonstrating how to use flag and index based tab-completion functions |
| 4 | +""" |
| 5 | +import argparse |
| 6 | +import functools |
| 7 | + |
| 8 | +import cmd2 |
| 9 | +from cmd2 import with_argparser, with_argument_list, flag_based_complete, index_based_complete |
| 10 | + |
| 11 | +# List of strings used with flag and index based completion functions |
| 12 | +food_item_strs = ['Pizza', 'Hamburger', 'Ham', 'Potato'] |
| 13 | +sport_item_strs = ['Bat', 'Basket', 'Basketball', 'Football'] |
| 14 | + |
| 15 | +# Dictionary used with flag based completion functions |
| 16 | +flag_dict = \ |
| 17 | + { |
| 18 | + '-f': food_item_strs, # Tab-complete food items after -f flag in command line |
| 19 | + '--food': food_item_strs, # Tab-complete food items after --food flag in command line |
| 20 | + '-s': sport_item_strs, # Tab-complete sport items after -s flag in command line |
| 21 | + '--sport': sport_item_strs, # Tab-complete sport items after --sport flag in command line |
| 22 | + } |
| 23 | + |
| 24 | +# Dictionary used with index based completion functions |
| 25 | +index_dict = \ |
| 26 | + { |
| 27 | + 1: food_item_strs, # Tab-complete food items at index 1 in command line |
| 28 | + 2: sport_item_strs, # Tab-complete sport items at index 2 in command line |
| 29 | + } |
| 30 | + |
| 31 | + |
| 32 | +class TabCompleteExample(cmd2.Cmd): |
| 33 | + """ Example cmd2 application where we a base command which has a couple subcommands.""" |
| 34 | + |
| 35 | + def __init__(self): |
| 36 | + cmd2.Cmd.__init__(self) |
| 37 | + |
| 38 | + add_item_parser = argparse.ArgumentParser() |
| 39 | + add_item_group = add_item_parser.add_mutually_exclusive_group() |
| 40 | + add_item_group.add_argument('-f', '--food', help='Adds food item') |
| 41 | + add_item_group.add_argument('-s', '--sport', help='Adds sport item') |
| 42 | + |
| 43 | + @with_argparser(add_item_parser) |
| 44 | + def do_add_item(self, args): |
| 45 | + """Add item command help""" |
| 46 | + if args.food: |
| 47 | + add_item = args.food |
| 48 | + elif args.sport: |
| 49 | + add_item = args.sport |
| 50 | + else: |
| 51 | + add_item = 'no items' |
| 52 | + |
| 53 | + self.poutput("You added {}".format(add_item)) |
| 54 | + |
| 55 | + # Add flag-based tab-completion to add_item command |
| 56 | + complete_add_item = functools.partial(flag_based_complete, flag_dict=flag_dict) |
| 57 | + |
| 58 | + @with_argument_list |
| 59 | + def do_list_item(self, args): |
| 60 | + """List item command help""" |
| 61 | + self.poutput("You listed {}".format(args)) |
| 62 | + |
| 63 | + # Add index-based tab-completion to list_item command |
| 64 | + complete_list_item = functools.partial(index_based_complete, index_dict=index_dict) |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == '__main__': |
| 68 | + app = TabCompleteExample() |
| 69 | + app.cmdloop() |
0 commit comments