Mercurial > hg > config
comparison python/example/cli.py @ 722:be9f792abaad
mv
| author | Jeff Hammel <k0scist@gmail.com> |
|---|---|
| date | Tue, 04 Nov 2014 15:11:08 -0800 |
| parents | python/cli.py@e7948549afa1 |
| children |
comparison
equal
deleted
inserted
replaced
| 721:2ebf5cef55de | 722:be9f792abaad |
|---|---|
| 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 try: | |
| 54 _dict, tags, args = main() | |
| 55 except ParserError, e: | |
| 56 import pdb; pdb.set_trace() # for debugging | |
| 57 print _dict | |
| 58 print tags | |
| 59 print args |
