summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rwxr-xr-xexamples/subcommands.py4
-rwxr-xr-xexamples/submenus.py109
-rwxr-xr-xexamples/tab_autocompletion.py31
3 files changed, 33 insertions, 111 deletions
diff --git a/examples/subcommands.py b/examples/subcommands.py
index 3dd2c683..55be7711 100755
--- a/examples/subcommands.py
+++ b/examples/subcommands.py
@@ -19,6 +19,10 @@ base_subparsers = base_parser.add_subparsers(title='subcommands', help='subcomma
parser_foo = base_subparsers.add_parser('foo', help='foo help')
parser_foo.add_argument('-x', type=int, default=1, help='integer')
parser_foo.add_argument('y', type=float, help='float')
+input_file = parser_foo.add_argument('input_file', type=str, help='Input File')
+if __name__ == '__main__':
+ from cmd2.argcomplete_bridge import bash_complete
+ bash_complete(input_file)
# create the parser for the "bar" subcommand
parser_bar = base_subparsers.add_parser('bar', help='bar help')
diff --git a/examples/submenus.py b/examples/submenus.py
deleted file mode 100755
index 27c8cb10..00000000
--- a/examples/submenus.py
+++ /dev/null
@@ -1,109 +0,0 @@
-#!/usr/bin/env python
-# coding=utf-8
-"""
-Create a CLI with a nested command structure as follows. The commands 'second' and 'third' navigate the CLI to the scope
-of the submenu. Nesting of the submenus is done with the cmd2.AddSubmenu() decorator.
-
- (Top Level)----second----->(2nd Level)----third----->(3rd Level)
- | | |
- ---> say ---> say ---> say
-"""
-from __future__ import print_function
-import sys
-
-from cmd2 import cmd2
-from IPython import embed
-
-
-class ThirdLevel(cmd2.Cmd):
- """To be used as a third level command class. """
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.prompt = '3rdLevel '
- self.top_level_attr = None
- self.second_level_attr = None
-
- def do_say(self, line):
- print("You called a command in ThirdLevel with '%s'. "
- "It has access to top_level_attr: %s "
- "and second_level_attr: %s" % (line, self.top_level_attr, self.second_level_attr))
-
- def help_say(self):
- print("This is a third level submenu (submenu_ab). Options are qwe, asd, zxc")
-
- def complete_say(self, text, line, begidx, endidx):
- return [s for s in ['qwe', 'asd', 'zxc'] if s.startswith(text)]
-
-
-@cmd2.AddSubmenu(ThirdLevel(),
- command='third',
- aliases=('third_alias',),
- shared_attributes=dict(second_level_attr='second_level_attr', top_level_attr='top_level_attr'))
-class SecondLevel(cmd2.Cmd):
- """To be used as a second level command class. """
- def __init__(self, *args, **kwargs):
- cmd2.Cmd.__init__(self, *args, **kwargs)
- self.prompt = '2ndLevel '
- self.top_level_attr = None
- self.second_level_attr = 987654321
-
- def do_ipy(self, arg):
- """Enters an interactive IPython shell.
-
- Run python code from external files with ``run filename.py``
- End with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``, '`exit()``.
- """
- banner = 'Entering an embedded IPython shell type quit() or <Ctrl>-d to exit ...'
- exit_msg = 'Leaving IPython, back to {}'.format(sys.argv[0])
- embed(banner1=banner, exit_msg=exit_msg)
-
- def do_say(self, line):
- print("You called a command in SecondLevel with '%s'. "
- "It has access to top_level_attr: %s" % (line, self.top_level_attr))
-
- def help_say(self):
- print("This is a SecondLevel menu. Options are qwe, asd, zxc")
-
- def complete_say(self, text, line, begidx, endidx):
- return [s for s in ['qwe', 'asd', 'zxc'] if s.startswith(text)]
-
-
-@cmd2.AddSubmenu(SecondLevel(),
- command='second',
- aliases=('second_alias',),
- shared_attributes=dict(top_level_attr='top_level_attr'))
-class TopLevel(cmd2.Cmd):
- """To be used as the main / top level command class that will contain other submenus."""
-
- def __init__(self, *args, **kwargs):
- cmd2.Cmd.__init__(self, *args, **kwargs)
- self.prompt = 'TopLevel '
- self.top_level_attr = 123456789
-
- def do_ipy(self, arg):
- """Enters an interactive IPython shell.
-
- Run python code from external files with ``run filename.py``
- End with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``, '`exit()``.
- """
- banner = 'Entering an embedded IPython shell type quit() or <Ctrl>-d to exit ...'
- exit_msg = 'Leaving IPython, back to {}'.format(sys.argv[0])
- embed(banner1=banner, exit_msg=exit_msg)
-
- def do_say(self, line):
- print("You called a command in TopLevel with '%s'. "
- "TopLevel has attribute top_level_attr=%s" % (line, self.top_level_attr))
-
- def help_say(self):
- print("This is a top level submenu. Options are qwe, asd, zxc")
-
- def complete_say(self, text, line, begidx, endidx):
- return [s for s in ['qwe', 'asd', 'zxc'] if s.startswith(text)]
-
-
-if __name__ == '__main__':
-
- root = TopLevel()
- root.cmdloop()
-
diff --git a/examples/tab_autocompletion.py b/examples/tab_autocompletion.py
index f3302533..adfe9702 100755
--- a/examples/tab_autocompletion.py
+++ b/examples/tab_autocompletion.py
@@ -96,6 +96,15 @@ class TabCompleteExample(cmd2.Cmd):
},
}
+ file_list = \
+ [
+ '/home/user/file.db',
+ '/home/user/file space.db',
+ '/home/user/another.db',
+ '/home/other user/maps.db',
+ '/home/other user/tests.db'
+ ]
+
def instance_query_actors(self) -> List[str]:
"""Simulating a function that queries and returns a completion values"""
return actors
@@ -225,9 +234,23 @@ class TabCompleteExample(cmd2.Cmd):
required=True)
actor_action = vid_movies_add_parser.add_argument('actor', help='Actors', nargs='*')
+ vid_movies_load_parser = vid_movies_commands_subparsers.add_parser('load')
+ vid_movie_file_action = vid_movies_load_parser.add_argument('movie_file', help='Movie database')
+
+ vid_movies_read_parser = vid_movies_commands_subparsers.add_parser('read')
+ vid_movie_fread_action = vid_movies_read_parser.add_argument('movie_file', help='Movie database')
+
# tag the action objects with completion providers. This can be a collection or a callable
setattr(director_action, argparse_completer.ACTION_ARG_CHOICES, static_list_directors)
- setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, instance_query_actors)
+ setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, 'instance_query_actors')
+
+ # tag the file property with a custom completion function 'delimeter_complete' provided by cmd2.
+ setattr(vid_movie_file_action, argparse_completer.ACTION_ARG_CHOICES,
+ ('delimiter_complete',
+ {'delimiter': '/',
+ 'match_against': file_list}))
+ setattr(vid_movie_fread_action, argparse_completer.ACTION_ARG_CHOICES,
+ ('path_complete', [False, False]))
vid_movies_delete_parser = vid_movies_commands_subparsers.add_parser('delete')
@@ -306,6 +329,9 @@ class TabCompleteExample(cmd2.Cmd):
movies_delete_parser = movies_commands_subparsers.add_parser('delete')
+ movies_load_parser = movies_commands_subparsers.add_parser('load')
+ movie_file_action = movies_load_parser.add_argument('movie_file', help='Movie database')
+
shows_parser = media_types_subparsers.add_parser('shows')
shows_parser.set_defaults(func=_do_media_shows)
@@ -333,7 +359,8 @@ class TabCompleteExample(cmd2.Cmd):
def complete_media(self, text, line, begidx, endidx):
""" Adds tab completion to media"""
choices = {'actor': query_actors, # function
- 'director': TabCompleteExample.static_list_directors # static list
+ 'director': TabCompleteExample.static_list_directors, # static list
+ 'movie_file': (self.path_complete, [False, False])
}
completer = argparse_completer.AutoCompleter(TabCompleteExample.media_parser, arg_choices=choices)