comparison flagReader.py @ 9:f807c5cfa0de

switched flagReader to optparse
author catherine@cordelia
date Thu, 15 May 2008 08:29:25 -0400
parents febfdc79550b
children 47af95ad83c7
comparison
equal deleted inserted replaced
8:a6284fa14e89 9:f807c5cfa0de
1 """Defines and parses UNIX-style flags to modify command arguments. 1 """Defines and parses UNIX-style flags to modify command arguments.
2
3 Use of flagReader is DEPRECATED in favor of optparse from the
4 Python standard library. For backwards compatibility, flagReader
5 has been re-implemented as a wrapper around optparse.
2 6
3 print flagReader.FlagSet.parse.__doc__ for usage examples. 7 print flagReader.FlagSet.parse.__doc__ for usage examples.
4 """ 8 """
5 9
6 import re 10 import re, optparse
7 11
8 class Flag(object): 12 class Flag(object):
9 def __init__(self, name, abbrev=None, nargs=0): 13 def __init__(self, name, abbrev=None, nargs=0):
10 """Flag(name, abbrev=None, nargs=0) : Defines a flag. 14 """Flag(name, abbrev=None, nargs=0) : Defines a flag.
11 15
54 >>> f.parse('hidden -bar') 58 >>> f.parse('hidden -bar')
55 ({}, 'hidden -bar') 59 ({}, 'hidden -bar')
56 >>> f.parse('-g myarg -b') 60 >>> f.parse('-g myarg -b')
57 ({'gimmea': ['myarg'], 'bar': []}, '') 61 ({'gimmea': ['myarg'], 'bar': []}, '')
58 """ 62 """
63 parser = optparse.OptionParser()
64 for flag in self.flags:
65 if flag.nargs:
66 parser.add_option(flag.fullabbrev, flag.fullname, action="store",
67 type="string", dest=flag.name)
68 else:
69 parser.add_option(flag.fullabbrev, flag.fullname, action="store_true",
70 dest=flag.name)
71 try:
72 (options, args) = parser.parse_args(arg.split())
73 except SystemExit, e:
74 return {}, arg
75
59 result = {} 76 result = {}
60 words = arg.split() 77 for (k,v) in options.__dict__.items():
61 while words: 78 if v == True:
62 word = words[0] 79 result[k] = []
63 flag = self.lookup.get(word) 80 elif v:
64 if flag: 81 result[k] = [v]
65 result[flag.name] = [] 82 return result, ' '.join(args)
66 words.pop(0)
67 for arg in range(flag.nargs):
68 try:
69 result[flag.name].append(words.pop(0))
70 except IndexError: # there aren't as many args as we expect
71 raise IndexError, '%s expects %d arguments' % (word, flag.nargs)
72 continue # on to next word
73 smashedAbbrevs = self.abbrevPattern.search(word)
74 if smashedAbbrevs:
75 for abbrev in smashedAbbrevs.group(1):
76 result[self.lookup[abbrev].name] = []
77 words.pop(0)
78 continue # on to next word
79 #if you get to here, word[0] does not denote options
80 break
81 return result, ' '.join(words)
82 83
83 def _test(): 84 def _test():
84 import doctest 85 import doctest
85 doctest.testmod() 86 doctest.testmod()
86 87