Debian Codegraph @

examples/cmd_as_argument.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """A sample application for cmd2.
3
4 This example has additional code in main() that shows how to accept a command from
5 the command line at invocation:
6
7 $ python cmd_as_argument.py speak -p hello there
8 """
9
10 import argparse
11 import secrets
12
13 import cmd2
14
15
16 class CmdLineApp(cmd2.Cmd):
17 """Example cmd2 application."""
18
19 MUMBLES = ("like", "...", "um", "er", "hmmm", "ahh")
20 MUMBLE_FIRST = ("so", "like", "well")
21 MUMBLE_LAST = ("right?",)
22
23 def __init__(self) -> None:
24 shortcuts = dict(cmd2.DEFAULT_SHORTCUTS)
25 shortcuts.update({"&": "speak"})
26 # Set include_ipy to True to enable the "ipy" command which runs an interactive IPython shell
27 super().__init__(allow_cli_args=False, include_ipy=True, multiline_commands=["orate"], shortcuts=shortcuts)
28
29 self.self_in_py = True
30 self.maxrepeats = 3
31 # Make maxrepeats settable at runtime
32 self.add_settable(cmd2.Settable("maxrepeats", int, "max repetitions for speak command", self))
33
34 # Create an instance of SystemRandom
35 self._secure_generator = secrets.SystemRandom()
36
37 speak_parser = cmd2.Cmd2ArgumentParser()
38 speak_parser.add_argument("-p", "--piglatin", action="store_true", help="atinLay")
39 speak_parser.add_argument("-s", "--shout", action="store_true", help="N00B EMULATION MODE")
40 speak_parser.add_argument("-r", "--repeat", type=int, help="output [n] times")
41 speak_parser.add_argument("words", nargs="+", help="words to say")
42
43 @cmd2.with_argparser(speak_parser)
44 def do_speak(self, args) -> None:
45 """Repeats what you tell me to."""
46 words = []
47 for w in args.words:
48 word = w.copy()
49 if args.piglatin:
50 word = f"{word[1:]}{word[0]}ay"
51 if args.shout:
52 word = word.upper()
53 words.append(word)
54 repetitions = args.repeat or 1
55 for _ in range(min(repetitions, self.maxrepeats)):
56 # .poutput handles newlines, and accommodates output redirection too
57 self.poutput(" ".join(words))
58
59 do_say = do_speak # now "say" is a synonym for "speak"
60 do_orate = do_speak # another synonym, but this one takes multi-line input
61
62 mumble_parser = cmd2.Cmd2ArgumentParser()
63 mumble_parser.add_argument("-r", "--repeat", type=int, help="how many times to repeat")
64 mumble_parser.add_argument("words", nargs="+", help="words to say")
65
66 @cmd2.with_argparser(mumble_parser)
67 def do_mumble(self, args) -> None:
68 """Mumbles what you tell me to."""
69 repetitions = args.repeat or 1
70 for _ in range(min(repetitions, self.maxrepeats)):
71 output = []
72 if self._secure_generator.random() < 0.33:
73 output.append(secrets.choice(self.MUMBLE_FIRST))
74 for word in args.words:
75 if self._secure_generator.random() < 0.40:
76 output.append(secrets.choice(self.MUMBLES))
77 output.append(word)
78 if self._secure_generator.random() < 0.25:
79 output.append(secrets.choice(self.MUMBLE_LAST))
80 self.poutput(" ".join(output))
81
82
83 def main(argv=None):
84 """Run when invoked from the operating system shell."""
85 parser = cmd2.Cmd2ArgumentParser(description="Commands as arguments")
86 command_help = "optional command to run, if no command given, enter an interactive shell"
87 parser.add_argument("command", nargs="?", help=command_help)
88 arg_help = "optional arguments for command"
89 parser.add_argument("command_args", nargs=argparse.REMAINDER, help=arg_help)
90
91 args = parser.parse_args(argv)
92
93 c = CmdLineApp()
94
95 sys_exit_code = 0
96 if args.command:
97 # we have a command, run it and then exit
98 c.onecmd_plus_hooks("{} {}".format(args.command, " ".join(args.command_args)))
99 else:
100 # we have no command, drop into interactive mode
101 sys_exit_code = c.cmdloop()
102
103 return sys_exit_code
104
105
106 if __name__ == "__main__":
107 import sys
108
109 sys.exit(main())