-
Notifications
You must be signed in to change notification settings - Fork 0
/
argparse-sample.py
67 lines (56 loc) · 2.45 KB
/
argparse-sample.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
import argparse
import logging
import sys
#-------------------------------------------------------------------------------
some_global = None
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# SDK wrappers
def utility(param):
pass
#-------------------------------------------------------------------------------
# CLI Functions
def foo(args):
utility(args.helloarg, args.fooarg)
def bar(args):
utility(args.helloarg, args.bararg)
def build(args):
utility(args.helloarg, None)
#-------------------------------------------------------------------------------
if __name__ == '__main__':
#-------------------------------------------------------------------------------
# Base parser
parser = argparse.ArgumentParser()
parser.add_argument('--verbose', '-v', action='store_true')
subparser = parser.add_subparsers()
hello_parser = subparser.add_parser('hello')
hello_parser.add_argument('--helloarg', default='val')
hello_parser.set_defaults(func=build)
#-------------------------------------------------------------------------------
# Parent parser for foo/bar, with parent argument
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument('--parent', type=int)
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Children parsers inheriting from parent_parser
foo_parser = subparser.add_parser('foo', help='foo help', parent_parsers=[parent_parser])
foo_parser.add_argument('--fooarg', default='foodef')
foo_parser.set_defaults(func=foo)
bar_parser = subparser.add_parser('bar', help='bar help', parent_parsers=[parent_parser])
bar_parser.add_argument('--bararg', '-b', action='store_true')
bar_parser.set_defaults(func=bar)
#-------------------------------------------------------------------------------
args = parser.parse_args()
log_level = logging.INFO
if args.verbose:
log_level = logging.DEBUG
logging.basicConfig(level=log_level, format='[*] %(message)s')
logger = logging.getLogger(__name__)
#---------------------------------------
if hasattr(args, 'func'):
args.func(args)
else:
parser.print_help()
#---------------------------------------
sys.exit()