-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_args.py
More file actions
112 lines (107 loc) · 4.42 KB
/
Copy pathparse_args.py
File metadata and controls
112 lines (107 loc) · 4.42 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import sys
from . import phelp
from . import parray
"""
Expects a list of arguments, without appropraite identifying metadata
Metadata includes:
name: always present, the name of the argument
flag: How it is identified, should only be present for - arguments (-p, -x, --long)
optional: whether the flag is optional (only for flags)
has_value: Whether the flag has a following value (i.e. -p <p name>)
These can't be chained (like -pvg for -p -v and -g)
type: Optional, The constructor for the type of the object (i.e. int)
It should be able to parse a string, i'm not responsible for what happens
if it can't. It defaults to a string
Returns a dictionary mapping names to the values (true for non-valued Named)
"""
def print_help ( desc, arglist, exit_code=1 ):
clargs = []
for arg in arglist:
name = arg.get('flag',arg.get('name',''))
_desc = arg.get('description','')
clargs.append((name,_desc))
phelp.phelp ( desc, clargs )
sys.exit(exit_code)
def parse_args ( desc, arglist ):
flags=[]
single_flags={"h": {"ishelp": True}}
long_flags={"--help": {"ishelp": True}}
necessaries=[]
for arg in arglist:
if arg.get('flag',"").startswith('-'):
flags.append(arg)
else:
necessaries.append(arg)
if arg.get("flag","").startswith("-"):
if arg.get("flag","").startswith("--"):
long_flags[arg["flag"]] = arg
else:
single_flags[arg["flag"][1:]] = arg
ret = {}
i = 1
while i < len(sys.argv):
arg = sys.argv[i]
if arg.startswith('-'):
cs = []
if ( arg.startswith('--') ):
cs.append(long_flags.get(arg))
else:
for l in arg[1:]:
cs.append(single_flags.get(l,{'flag': l}))
for c in cs:
if c.get('ishelp'):
print_help(desc, arglist,0)
elif 'name' not in c:
print("Unrecognized argument '{}'".format(c['flag']))
print_help(desc, arglist)
else:
if c.get('has'):
print("Already received argument '{}'".format(c['flag']))
print_help(desc, arglist)
val = True
if c.get('has_value'):
if ( len ( sys.argv ) < i+2 ):
print("'{}' Should be followed by an argument".format(c['flag']))
print_help(desc, arglist)
val = sys.argv[i+1]
if 'type' in c:
try:
val = c['type'](val)
except:
print("'{}' is not of correct type".format(val))
print_help(desc, arglist)
i += 1
ret[c['name']] = val
c['has'] = True
else:
if ( len ( necessaries ) > 0 ):
c = necessaries.pop(0)
val = arg
if 'type' in c:
try:
val = c['type'](val)
except:
print("'{}' is not of correct type".format(val))
print_help(desc, arglist)
ret[c['name']] = val
else:
print("Extra argument '{}'".format(arg))
print_help(desc, arglist)
i += 1
names=[]
for n in necessaries:
names.append(n['name'])
for n in flags:
if not n.get('optional',False) and not 'has' in n:
names.append("{} ({})".format(n['flag'],n['name']))
if len ( names ) > 0:
print("Missing arguments: {}".format(parray.parray(names)))
print_help(desc, arglist)
return ret
"""
print parse_args ( "I am a test description", [ { 'name': 'present', 'flag': '-p', 'optional': True, 'has_value': True, 'type': int, 'description': 'This specifies to make the file present' },
{ 'name': 'cool', 'flag': '-x', 'description': 'Determined whether it is cool' },
{ 'name': 'filename', 'description': 'The file name to use bro' },
{ 'name': 'use_long', 'flag': '--long', 'optional': True, 'description': 'use long ints' },
{ 'name': 'doggo', 'description': 'Whether or not doggo' }] )
"""