Mercurial > hg > config
comparison python/cli.py @ 107:1da1baa03ac1
add a cli example program
| author | Jeff Hammel <jhammel@mozilla.com> |
|---|---|
| date | Mon, 29 Nov 2010 07:21:30 -0800 |
| parents | |
| children | e7948549afa1 |
comparison
equal
deleted
inserted
replaced
| 106:3c193788a0db | 107:1da1baa03ac1 |
|---|---|
| 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 |
