Debian Codegraph @

examples/basic_completion.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """A simple example demonstrating how to enable tab completion by assigning a completer function to do_* commands.
3
4 This also demonstrates capabilities of the following completer features included with cmd2:
5 - CompletionError exceptions
6 - delimiter_complete()
7
8 The recommended approach for tab completing is to use argparse-based completion.
9 For an example integrating tab completion with argparse, see argparse_completion.py.
10 """
11
12 import functools
13 from typing import NoReturn
14
15 import cmd2
16
17 # This data is used to demonstrate delimiter_complete
18 file_strs = [
19 "/home/user/file.db",
20 "/home/user/file space.db",
21 "/home/user/another.db",
22 "/home/other user/maps.db",
23 "/home/other user/tests.db",
24 ]
25
26
27 class BasicCompletion(cmd2.Cmd):
28 def __init__(self) -> None:
29 super().__init__(auto_suggest=False, include_py=True)
30
31 def do_delimiter_complete(self, statement: cmd2.Statement) -> None:
32 """Tab completes files from a list using delimiter_complete."""
33 self.poutput(f"Args: {statement.args}")
34
35 # Use a partialmethod to set arguments to delimiter_complete
36 complete_delimiter_complete = functools.partialmethod(cmd2.Cmd.delimiter_complete, match_against=file_strs, delimiter="/")
37
38 def do_raise_error(self, statement: cmd2.Statement) -> None:
39 """Demonstrates effect of raising CompletionError."""
40 self.poutput(f"Args: {statement.args}")
41
42 def complete_raise_error(self, _text: str, _line: str, _begidx: int, _endidx: int) -> NoReturn:
43 """CompletionErrors can be raised if an error occurs while tab completing.
44
45 Example use cases
46 - Reading a database to retrieve a tab completion data set failed
47 - A previous command line argument that determines the data set being completed is invalid
48 """
49 raise cmd2.CompletionError("This is how a CompletionError behaves")
50
51
52 if __name__ == "__main__":
53 import sys
54
55 app = BasicCompletion()
56 sys.exit(app.cmdloop())