Debian Codegraph @

examples/python_scripting.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """A sample application for how Python scripting can provide conditional
3 control flow of a cmd2 application.
4
5 cmd2's built-in scripting capability, which can be invoked via the "@" shortcut
6 or "run_script" command, uses basic ASCII/UTF-8 text scripts and is very easy
7 to use. Moreover, the trivial syntax of the script files, where there is one
8 command per line and the line is exactly what the user would type inside the
9 application, makes it so non-technical that end users can quickly learn to
10 create scripts.
11
12 However, there comes a time when technical end users want more capability and
13 power. In particular it is common that users will want to create a script with
14 conditional control flow - where the next command run will depend on the
15 results from the previous command. This is where the ability to run Python
16 scripts inside a cmd2 application via the run_pyscript command and the
17 "run_pyscript <script> [arguments]" syntax comes into play.
18
19 This application and the "examples/scripts/conditional.py" script serve as an
20 example for one way in which this can be done.
21 """
22
23 import argparse
24 import os
25
26 import cmd2
27 from cmd2 import (
28 Color,
29 stylize,
30 )
31
32
33 class CmdLineApp(cmd2.Cmd):
34 """Example cmd2 application to showcase conditional control flow in Python scripting within cmd2 apps."""
35
36 def __init__(self) -> None:
37 # Set include_ipy to True to enable the "ipy" command which runs an interactive IPython shell
38 super().__init__(include_ipy=True)
39 self._set_prompt()
40 self.intro = "Happy 𝛑 Day. Note the full Unicode support: 😇 💩"
41
42 def _set_prompt(self) -> None:
43 """Set prompt so it displays the current working directory."""
44 self.cwd = os.getcwd()
45 self.prompt = stylize(f"{self.cwd} $ ", style=Color.CYAN)
46
47 def postcmd(self, stop: bool, _line: str) -> bool:
48 """Hook method executed just after a command dispatch is finished.
49
50 :param stop: if True, the command has indicated the application should exit
51 :param line: the command line text for this command
52 :return: if this is True, the application will exit after this command and the postloop() will run
53 """
54 """Override this so prompt always displays cwd."""
55 self._set_prompt()
56 return stop
57
58 @cmd2.with_argument_list
59 def do_cd(self, arglist: list[str]) -> None:
60 """Change directory.
61 Usage:
62 cd <new_dir>.
63 """
64 # Expect 1 argument, the directory to change to
65 if not arglist or len(arglist) != 1:
66 self.perror("cd requires exactly 1 argument:")
67 self.do_help("cd")
68 self.last_result = "Bad arguments"
69 return
70
71 # Convert relative paths to absolute paths
72 path = os.path.abspath(os.path.expanduser(arglist[0]))
73
74 # Make sure the directory exists, is a directory, and we have read access
75 err = None
76 data = None
77 if not os.path.isdir(path):
78 err = f"{path} is not a directory"
79 elif not os.access(path, os.R_OK):
80 err = f"You do not have read access to {path}"
81 else:
82 try:
83 os.chdir(path)
84 except Exception as ex: # noqa: BLE001
85 err = f"{ex}"
86 else:
87 self.poutput(f"Successfully changed directory to {path}")
88 data = path
89
90 if err:
91 self.perror(err)
92 self.last_result = data
93
94 # Enable tab completion for cd command
95 def complete_cd(self, text: str, line: str, begidx: int, endidx: int) -> list[str]:
96 # Tab complete only directories
97 return self.path_complete(text, line, begidx, endidx, path_filter=os.path.isdir)
98
99 dir_parser = cmd2.Cmd2ArgumentParser()
100 dir_parser.add_argument("-l", "--long", action="store_true", help="display in long format with one item per line")
101
102 @cmd2.with_argparser(dir_parser, with_unknown_args=True)
103 def do_dir(self, _args: argparse.Namespace, unknown: list[str]) -> None:
104 """List contents of current directory."""
105 # No arguments for this command
106 if unknown:
107 self.perror("dir does not take any positional arguments:")
108 self.do_help("dir")
109 self.last_result = "Bad arguments"
110 return
111
112 # Get the contents as a list
113 contents = os.listdir(self.cwd)
114
115 for f in contents:
116 self.poutput(f"{f}")
117 self.poutput("")
118
119 self.last_result = contents
120
121
122 if __name__ == "__main__":
123 import sys
124
125 c = CmdLineApp()
126 sys.exit(c.cmdloop())