diff options
author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2018-01-15 12:11:12 -0500 |
---|---|---|
committer | Todd Leonhardt <todd.leonhardt@gmail.com> | 2018-01-15 12:11:12 -0500 |
commit | eee2d621abfb3d6455570b540069a4853a68f8c6 (patch) | |
tree | 6bfc049369079868eab6f05ce8d0cae233c43cb9 /examples/python_scripting.py | |
parent | aec6704db9542e35e4cdc6073210bc0d6c507335 (diff) | |
download | cmd2-git-eee2d621abfb3d6455570b540069a4853a68f8c6.tar.gz |
Changed @with_argument_parser to only pass single argument to commands
Also added another @with_argparser_and_list decorator that uses argparse.parse_known_args to pass two arguments to a command: both the argparse output and a list of unknown/unmatched args.
Diffstat (limited to 'examples/python_scripting.py')
-rwxr-xr-x | examples/python_scripting.py | 18 |
1 files changed, 10 insertions, 8 deletions
diff --git a/examples/python_scripting.py b/examples/python_scripting.py index 68290a7b..a2892dc8 100755 --- a/examples/python_scripting.py +++ b/examples/python_scripting.py @@ -14,11 +14,11 @@ command and the "pyscript <script> [arguments]" syntax comes into play. This application and the "scripts/conditional.py" script serve as an example for one way in which this can be done. """ +import argparse import functools import os -from cmd2 import Cmd, options, CmdResult, with_argument_list -from optparse import make_option +from cmd2 import Cmd, CmdResult, with_argument_list, with_argparser_and_list class CmdLineApp(Cmd): @@ -86,13 +86,15 @@ class CmdLineApp(Cmd): # Enable directory completion for cd command by freezing an argument to path_complete() with functools.partialmethod complete_cd = functools.partialmethod(Cmd.path_complete, dir_only=True) - @options([make_option('-l', '--long', action="store_true", help="display in long format with one item per line")], - arg_desc='') - def do_dir(self, arg, opts=None): + dir_parser = argparse.ArgumentParser() + dir_parser.add_argument('-l', '--long', action='store_true', help="display in long format with one item per line") + + @with_argparser_and_list(dir_parser) + def do_dir(self, args, unknown): """List contents of current directory.""" # No arguments for this command - if arg: - self.perror("dir does not take any arguments:", traceback_war=False) + if unknown: + self.perror("dir does not take any positional arguments:", traceback_war=False) self.do_help('dir') self._last_result = CmdResult('', 'Bad arguments') return @@ -101,7 +103,7 @@ class CmdLineApp(Cmd): contents = os.listdir(self.cwd) fmt = '{} ' - if opts.long: + if args.long: fmt = '{}\n' for f in contents: self.stdout.write(fmt.format(f)) |