diff options
author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2018-07-29 23:06:06 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-07-29 23:06:06 -0700 |
commit | 573d15705bfa57a22b63010796d76c9ba5f7be3b (patch) | |
tree | 90d5257c486ceb6693ad9ad6b65ade28b98bcb58 /examples/cmd_as_argument.py | |
parent | 34adfe4bf24b825095337fb272b9ba98eccbe714 (diff) | |
parent | 029d734521fdd8de51cf819a75f0708d66ea4751 (diff) | |
download | cmd2-git-573d15705bfa57a22b63010796d76c9ba5f7be3b.tar.gz |
Merge pull request #482 from python-cmd2/run_at_invocation
Add example and documentation for #452
Diffstat (limited to 'examples/cmd_as_argument.py')
-rwxr-xr-x | examples/cmd_as_argument.py | 114 |
1 files changed, 114 insertions, 0 deletions
diff --git a/examples/cmd_as_argument.py b/examples/cmd_as_argument.py new file mode 100755 index 00000000..eb46eedf --- /dev/null +++ b/examples/cmd_as_argument.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python +# coding=utf-8 +""" +A sample application for cmd2. + +This example is very similar to example.py, but had additional +code in main() that shows how to accept a command from +the command line at invocation: + +$ python cmd_as_argument.py speak -p hello there + + +""" + +import argparse +import random +import sys + +import cmd2 + + +class CmdLineApp(cmd2.Cmd): + """ Example cmd2 application. """ + + # Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist + # default_to_shell = True + MUMBLES = ['like', '...', 'um', 'er', 'hmmm', 'ahh'] + MUMBLE_FIRST = ['so', 'like', 'well'] + MUMBLE_LAST = ['right?'] + + def __init__(self): + self.allow_cli_args = False + self.multiline_commands = ['orate'] + self.maxrepeats = 3 + + # Add stuff to settable and shortcuts before calling base class initializer + self.settable['maxrepeats'] = 'max repetitions for speak command' + self.shortcuts.update({'&': 'speak'}) + + # Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell + super().__init__(use_ipython=False) + + speak_parser = argparse.ArgumentParser() + speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay') + speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE') + speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times') + speak_parser.add_argument('words', nargs='+', help='words to say') + + @cmd2.with_argparser(speak_parser) + def do_speak(self, args): + """Repeats what you tell me to.""" + words = [] + for word in args.words: + if args.piglatin: + word = '%s%say' % (word[1:], word[0]) + if args.shout: + word = word.upper() + words.append(word) + repetitions = args.repeat or 1 + for i in range(min(repetitions, self.maxrepeats)): + # .poutput handles newlines, and accommodates output redirection too + self.poutput(' '.join(words)) + + do_say = do_speak # now "say" is a synonym for "speak" + do_orate = do_speak # another synonym, but this one takes multi-line input + + mumble_parser = argparse.ArgumentParser() + mumble_parser.add_argument('-r', '--repeat', type=int, help='how many times to repeat') + mumble_parser.add_argument('words', nargs='+', help='words to say') + + @cmd2.with_argparser(mumble_parser) + def do_mumble(self, args): + """Mumbles what you tell me to.""" + repetitions = args.repeat or 1 + for i in range(min(repetitions, self.maxrepeats)): + output = [] + if random.random() < .33: + output.append(random.choice(self.MUMBLE_FIRST)) + for word in args.words: + if random.random() < .40: + output.append(random.choice(self.MUMBLES)) + output.append(word) + if random.random() < .25: + output.append(random.choice(self.MUMBLE_LAST)) + self.poutput(' '.join(output)) + + +def main(argv=None): + """Run when invoked from the operating system shell""" + + parser = argparse.ArgumentParser( + description='Commands as arguments' + ) + command_help = 'optional command to run, if no command given, enter an interactive shell' + parser.add_argument('command', nargs='?', + help=command_help) + arg_help = 'optional arguments for command' + parser.add_argument('command_args', nargs=argparse.REMAINDER, + help=arg_help) + + args = parser.parse_args(argv) + + c = CmdLineApp() + + if args.command: + # we have a command, run it and then exit + c.onecmd_plus_hooks('{} {}'.format(args.command, ' '.join(args.command_args))) + else: + # we have no command, drop into interactive mode + c.cmdloop() + + +if __name__ == '__main__': + sys.exit(main())
\ No newline at end of file |