Last active
August 29, 2018 14:52
-
-
Save dboyliao/43ff6ce606beaadba844a939a371be9a to your computer and use it in GitHub Desktop.
argparse example part 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # coding: utf8 | |
| import sys | |
| import subprocess | |
| import argparse | |
| from pathlib import Path | |
| def ls(path, flags=None): | |
| if not flags: | |
| flags = [] | |
| if ~path.is_dir() or ~path.exists(): | |
| print(f'{path!s} does not exist or is not a directory') | |
| return 1 | |
| cmd = ['ls'] + flags + [str(path)] | |
| return subprocess.call(cmd) | |
| def man(what, n=1): | |
| cmd = ['man'] + [str(n)] + [what] | |
| return subprocess.call(cmd) | |
| def echo(msg): | |
| print(msg) | |
| return 0 | |
| def _build_parser(): | |
| parser = argparse.ArgumentParser() | |
| subcmd = parser.add_subparsers( | |
| dest='subcmd', help='subcommands', metavar='SUBCOMMAND') | |
| subcmd.required = True | |
| # ls | |
| ls_parser = subcmd.add_parser('ls', | |
| help='listing given directory') | |
| ls_parser.add_argument('path', | |
| type=Path, | |
| help='path of the directory', | |
| metavar='DIR') | |
| ls_parser.add_argument('--flag', | |
| dest='flags', | |
| help='flag for ls command (multiple flag)', | |
| action='append') | |
| # man | |
| man_parser = subcmd.add_parser('man', | |
| help='show man page') | |
| man_parser.add_argument('what') | |
| man_parser.add_argument('-n', type=int, help='section number') | |
| # echo | |
| echo_parser = subcmd.add_parser('echo', | |
| help='echo a given message') | |
| echo_parser.add_argument('msg', help='the message', metavar='\'MESSAGE\'') | |
| return parser | |
| if __name__ == '__main__': | |
| parser = _build_parser() | |
| args = parser.parse_args() | |
| if args.subcmd == 'ls': | |
| ret = ls(args.path, args.flags) | |
| elif args.subcmd == 'man': | |
| ret = man(args.what, n=args.n) | |
| else: | |
| ret = echo(args.msg) | |
| sys.exit(ret) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment