Mercurial > hg > configuration
comparison example/dictarg.py @ 137:bbe1d192a61c
sample
| author | Jeff Hammel <k0scist@gmail.com> |
|---|---|
| date | Tue, 04 Nov 2014 15:09:08 -0800 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 136:b97c454cfa3b | 137:bbe1d192a61c |
|---|---|
| 1 #!/usr/bin/python | |
| 2 | |
| 3 import sys | |
| 4 | |
| 5 def dictarg(adict, argv=sys.argv[1:]): | |
| 6 | |
| 7 shopts = {} | |
| 8 | |
| 9 # build list of keys | |
| 10 for i in adict.keys(): | |
| 11 for j in i: | |
| 12 s = str(j) | |
| 13 if len(s) == 1: | |
| 14 if shopts.has_key(s): | |
| 15 continue | |
| 16 shopts[s] = i | |
| 17 break | |
| 18 else: | |
| 19 print >> sys.stderr, "dictarg: couldn't generate key for '%s'" % i | |
| 20 sys.exit(1) | |
| 21 | |
| 22 optstring = "?" | |
| 23 for i in shopts.keys(): | |
| 24 optstring += i + ':' # all these options should have arguments | |
| 25 | |
| 26 # look for command line args | |
| 27 import getopt | |
| 28 | |
| 29 opts, args = getopt.getopt(argv, optstring) | |
| 30 | |
| 31 if ('-?', '') in opts: | |
| 32 print 'Options:' | |
| 33 for i in shopts: | |
| 34 print '-%s %s [%s]' % (i, shopts[i], adict[shopts[i]]) | |
| 35 sys.exit(0) | |
| 36 | |
| 37 for o, v in opts: | |
| 38 o = o[1:] # cut off the dash | |
| 39 adict[shopts[o]] = v | |
| 40 | |
| 41 # test if invoked from command line | |
| 42 if __name__ == '__main__': | |
| 43 adict = {} | |
| 44 for i in sys.argv: | |
| 45 adict[i] = len(i) | |
| 46 | |
| 47 # print the help | |
| 48 dictarg(adict, ['-?']) | |
| 49 | |
| 50 # test functionality | |
| 51 print 'Enter test arguments: ', | |
| 52 line = sys.stdin.readline()[:-1].split(' ') | |
| 53 dictarg(adict, line) | |
| 54 print adict |
