options.py (13709:dd6b7ac5801f) options.py (13714:35636064b7a1)
1# Copyright (c) 2005 The Regents of The University of Michigan
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met: redistributions of source code must retain the above copyright
7# notice, this list of conditions and the following disclaimer;
8# redistributions in binary form must reproduce the above copyright
9# notice, this list of conditions and the following disclaimer in the
10# documentation and/or other materials provided with the distribution;
11# neither the name of the copyright holders nor the names of its
12# contributors may be used to endorse or promote products derived from
13# this software without specific prior written permission.
14#
15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26#
27# Authors: Nathan Binkert
28
1# Copyright (c) 2005 The Regents of The University of Michigan
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met: redistributions of source code must retain the above copyright
7# notice, this list of conditions and the following disclaimer;
8# redistributions in binary form must reproduce the above copyright
9# notice, this list of conditions and the following disclaimer in the
10# documentation and/or other materials provided with the distribution;
11# neither the name of the copyright holders nor the names of its
12# contributors may be used to endorse or promote products derived from
13# this software without specific prior written permission.
14#
15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26#
27# Authors: Nathan Binkert
28
29from __future__ import print_function
30from __future__ import absolute_import
31
29import optparse
30import sys
31
32from optparse import *
33
34class nodefault(object): pass
35
36class splitter(object):
37 def __init__(self, split):
38 self.split = split
39 def __call__(self, option, opt_str, value, parser):
40 values = value.split(self.split)
41 dest = getattr(parser.values, option.dest)
42 if dest is None:
43 setattr(parser.values, option.dest, values)
44 else:
45 dest.extend(values)
46
47class OptionParser(dict):
48 def __init__(self, *args, **kwargs):
49 kwargs.setdefault('formatter', optparse.TitledHelpFormatter())
50 self._optparse = optparse.OptionParser(*args, **kwargs)
51 self._optparse.disable_interspersed_args()
52
53 self._allopts = {}
54
55 # current option group
56 self._group = self._optparse
57
58 def set_defaults(self, *args, **kwargs):
59 return self._optparse.set_defaults(*args, **kwargs)
60
61 def set_group(self, *args, **kwargs):
62 '''set the current option group'''
63 if not args and not kwargs:
64 self._group = self._optparse
65 else:
66 self._group = self._optparse.add_option_group(*args, **kwargs)
67
68 def add_option(self, *args, **kwargs):
69 '''add an option to the current option group, or global none set'''
70
71 # if action=split, but allows the option arguments
72 # themselves to be lists separated by the split variable'''
73
74 if kwargs.get('action', None) == 'append' and 'split' in kwargs:
75 split = kwargs.pop('split')
76 kwargs['default'] = []
77 kwargs['type'] = 'string'
78 kwargs['action'] = 'callback'
79 kwargs['callback'] = splitter(split)
80
81 option = self._group.add_option(*args, **kwargs)
82 dest = option.dest
83 if dest not in self._allopts:
84 self._allopts[dest] = option
85
86 return option
87
88 def bool_option(self, name, default, help):
89 '''add a boolean option called --name and --no-name.
90 Display help depending on which is the default'''
91
92 tname = '--%s' % name
93 fname = '--no-%s' % name
94 dest = name.replace('-', '_')
95 if default:
96 thelp = optparse.SUPPRESS_HELP
97 fhelp = help
98 else:
99 thelp = help
100 fhelp = optparse.SUPPRESS_HELP
101
102 topt = self.add_option(tname, action="store_true", default=default,
103 help=thelp)
104 fopt = self.add_option(fname, action="store_false", dest=dest,
105 help=fhelp)
106
107 return topt,fopt
108
109 def __getattr__(self, attr):
110 if attr.startswith('_'):
111 return super(OptionParser, self).__getattribute__(attr)
112
113 if attr in self:
114 return self[attr]
115
116 return super(OptionParser, self).__getattribute__(attr)
117
118 def __setattr__(self, attr, value):
119 if attr.startswith('_'):
120 super(OptionParser, self).__setattr__(attr, value)
121 elif attr in self._allopts:
122 defaults = { attr : value }
123 self.set_defaults(**defaults)
124 if attr in self:
125 self[attr] = value
126 else:
127 super(OptionParser, self).__setattr__(attr, value)
128
129 def parse_args(self):
130 opts,args = self._optparse.parse_args()
131
132 for key,val in opts.__dict__.items():
133 if val is not None or key not in self:
134 self[key] = val
135
136 return args
137
138 def usage(self, exitcode=None):
139 self._optparse.print_help()
140 if exitcode is not None:
141 sys.exit(exitcode)
142
32import optparse
33import sys
34
35from optparse import *
36
37class nodefault(object): pass
38
39class splitter(object):
40 def __init__(self, split):
41 self.split = split
42 def __call__(self, option, opt_str, value, parser):
43 values = value.split(self.split)
44 dest = getattr(parser.values, option.dest)
45 if dest is None:
46 setattr(parser.values, option.dest, values)
47 else:
48 dest.extend(values)
49
50class OptionParser(dict):
51 def __init__(self, *args, **kwargs):
52 kwargs.setdefault('formatter', optparse.TitledHelpFormatter())
53 self._optparse = optparse.OptionParser(*args, **kwargs)
54 self._optparse.disable_interspersed_args()
55
56 self._allopts = {}
57
58 # current option group
59 self._group = self._optparse
60
61 def set_defaults(self, *args, **kwargs):
62 return self._optparse.set_defaults(*args, **kwargs)
63
64 def set_group(self, *args, **kwargs):
65 '''set the current option group'''
66 if not args and not kwargs:
67 self._group = self._optparse
68 else:
69 self._group = self._optparse.add_option_group(*args, **kwargs)
70
71 def add_option(self, *args, **kwargs):
72 '''add an option to the current option group, or global none set'''
73
74 # if action=split, but allows the option arguments
75 # themselves to be lists separated by the split variable'''
76
77 if kwargs.get('action', None) == 'append' and 'split' in kwargs:
78 split = kwargs.pop('split')
79 kwargs['default'] = []
80 kwargs['type'] = 'string'
81 kwargs['action'] = 'callback'
82 kwargs['callback'] = splitter(split)
83
84 option = self._group.add_option(*args, **kwargs)
85 dest = option.dest
86 if dest not in self._allopts:
87 self._allopts[dest] = option
88
89 return option
90
91 def bool_option(self, name, default, help):
92 '''add a boolean option called --name and --no-name.
93 Display help depending on which is the default'''
94
95 tname = '--%s' % name
96 fname = '--no-%s' % name
97 dest = name.replace('-', '_')
98 if default:
99 thelp = optparse.SUPPRESS_HELP
100 fhelp = help
101 else:
102 thelp = help
103 fhelp = optparse.SUPPRESS_HELP
104
105 topt = self.add_option(tname, action="store_true", default=default,
106 help=thelp)
107 fopt = self.add_option(fname, action="store_false", dest=dest,
108 help=fhelp)
109
110 return topt,fopt
111
112 def __getattr__(self, attr):
113 if attr.startswith('_'):
114 return super(OptionParser, self).__getattribute__(attr)
115
116 if attr in self:
117 return self[attr]
118
119 return super(OptionParser, self).__getattribute__(attr)
120
121 def __setattr__(self, attr, value):
122 if attr.startswith('_'):
123 super(OptionParser, self).__setattr__(attr, value)
124 elif attr in self._allopts:
125 defaults = { attr : value }
126 self.set_defaults(**defaults)
127 if attr in self:
128 self[attr] = value
129 else:
130 super(OptionParser, self).__setattr__(attr, value)
131
132 def parse_args(self):
133 opts,args = self._optparse.parse_args()
134
135 for key,val in opts.__dict__.items():
136 if val is not None or key not in self:
137 self[key] = val
138
139 return args
140
141 def usage(self, exitcode=None):
142 self._optparse.print_help()
143 if exitcode is not None:
144 sys.exit(exitcode)
145