107
|
1 #!/usr/bin/env python
|
|
2
|
|
3 """
|
|
4 program illustrating command line in the form of
|
|
5 ``--option foo`` or ``--option=foo`` goes to a (key,value) paid
|
|
6 and ``-tag`` gets appended to a list. Further options go to a further list::
|
|
7
|
|
8 >>> main(['-foo', '--bar=fleem', 'baz'])
|
|
9 (['foo'], {'bar': 'fleem'}, ['baz'])
|
|
10 """
|
|
11
|
|
12 import sys
|
|
13
|
|
14 class ParserError(Exception):
|
|
15 """error for exceptions while parsing the command line"""
|
|
16
|
|
17 def main(_args=sys.argv[1:]):
|
|
18
|
|
19 # return values
|
|
20 _dict = {}
|
|
21 tags = []
|
|
22 args = []
|
|
23
|
|
24 # parse the arguments
|
|
25 key = None
|
|
26 for arg in _args:
|
|
27 if arg.startswith('---'):
|
|
28 raise ParserError("arguments should start with '-' or '--' only")
|
|
29 elif arg.startswith('--'):
|
|
30 if key:
|
|
31 raise ParserError("Key %s still open" % key)
|
|
32 key = arg[2:]
|
|
33 if '=' in key:
|
|
34 key, value = key.split('=', 1)
|
|
35 _dict[key] = value
|
|
36 key = None
|
|
37 continue
|
|
38 elif arg.startswith('-'):
|
|
39 if key:
|
|
40 raise ParserError("Key %s still open" % key)
|
|
41 tags.append(arg[1:])
|
|
42 continue
|
|
43 else:
|
|
44 if key:
|
|
45 _dict[key] = arg
|
|
46 continue
|
|
47 args.append(arg)
|
|
48
|
|
49 # return values
|
|
50 return (_dict, tags, args)
|
|
51
|
|
52 if __name__ == '__main__':
|
|
53 _dict, tags, args = main()
|
|
54 print _dict
|
|
55 print tags
|
|
56 print args
|