-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArgsParse.py
67 lines (59 loc) · 1.52 KB
/
ArgsParse.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
import re
"""
>>> p = ArgParse()
>>> p.addOption('-p')
>>> '-p' in p.options
True
>>> args = ['-l 12']
>>> p.options['-p'](args)
True
>>> args
['-l 12']
"""
class ArgParse:
def __init__(self):
self.options = {}
"""Adds an option that can either be set or not.
"""
def addOption(self, name):
def parseValue(args):
return True
self.options[name] = parseValue
def addInteger(self, name):
def parseValue(args):
if len(args) > 0:
return int(args.pop(0))
else:
raise ValueError('Missing value for argument')
self.options[name] = parseValue
def addString(self, name):
def parseValue(args):
if(len(args) > 0):
return args.pop(0)
else:
raise ValueError('Missing value for argument')
self.options[name] = parseValue
def parse(self, args):
# a flag is a - together with a letter
# flags must be either proceeded or succeeded by a space (except start/end of string)
tokens = re.split('((?:^| )-[a-zA-Z](?= |$))', args)
# remove all empty tokens and strip leading/trailing whitespace
tokens = [t.strip() for t in tokens if t]
result = {}
while len(tokens) > 0:
flag = tokens.pop(0)
if not flag.startswith('-'):
raise ValueError('Unexpected Value: ' + flag)
if flag in self.options:
result[flag] = self.options[flag](tokens)
else:
raise ValueError('Unkown Parameter: ' + flag)
return result
if __name__ == '__main__':
import doctest
doctest.testmod()
p = ArgParse()
p.addOption('-l')
p.addInteger('-p')
p.addString('-d')
print(p.parse('-l -p 8080 -d /usr-foo/logs'))