blob: 36fcba1589adc7cb7495928556773fa10a865673 [file] [log] [blame]
Michael Walsh7423c012016-10-04 10:27:21 -05001#!/usr/bin/env python
2
3r"""
4This module provides valuable argument processing functions like
5gen_get_options and sprint_args.
6"""
7
8import sys
9import __builtin__
10import atexit
11import signal
12import argparse
13
14import gen_print as gp
15
16default_string = ' The default value is "%(default)s".'
17
18
19###############################################################################
20def gen_get_options(parser,
21 stock_list=[]):
22
23 r"""
24 Parse the command line arguments using the parser object passed and return
25 True/False (i.e. pass/fail). Also set the following built in values:
26
27 __builtin__.quiet This value is used by the qprint functions.
28 __builtin__.test_mode This value is used by command processing functions.
29 __builtin__.debug This value is used by the dprint functions.
30 __builtin__.arg_obj This value is used by print_program_header, etc.
31 __builtin__.parser This value is used by print_program_header, etc.
32
33 Description of arguments:
34 parser A parser object. See argparse module
35 documentation for details.
36 stock_list The caller can use this parameter to
37 request certain stock parameters offered
38 by this function. For example, this
39 function will define a "quiet" option upon
40 request. This includes stop help text and
41 parm checking. The stock_list is a list
42 of tuples each of which consists of an
43 arg_name and a default value. Example:
44 stock_list = [("test_mode", 0), ("quiet",
45 1), ("debug", 0)]
46 """
47
48 # This is a list of stock parms that we support.
49 master_stock_list = ["quiet", "test_mode", "debug", "loglevel"]
50
51 # Process stock_list.
52 for ix in range(0, len(stock_list)):
53 if len(stock_list[ix]) < 1:
54 gp.print_error_report("Programmer error - stock_list[" + str(ix) +
55 "] is supposed to be a tuple containing at" +
56 " least one element which is the name of" +
57 " the desired stock parameter:\n" +
58 gp.sprint_var(stock_list))
59 return False
60 if type(stock_list[ix]) is tuple:
61 arg_name = stock_list[ix][0]
62 default = stock_list[ix][1]
63 else:
64 arg_name = stock_list[ix]
65 default = None
66
67 if arg_name not in master_stock_list:
68 gp.pvar(arg_name)
69 gp.print_error_report("Programmer error - \"" + arg_name +
70 "\" not found found in stock list:\n" +
71 gp.sprint_var(master_stock_list))
72 return False
73
74 if arg_name == "quiet":
75 if default is None:
76 default = 0
77 parser.add_argument(
78 '--quiet',
79 default=default,
80 type=int,
81 choices=[1, 0],
82 help='If this parameter is set to "1", %(prog)s' +
83 ' will print only essential information, i.e. it will' +
84 ' not echo parameters, echo commands, print the total' +
Michael Walshc33ef372017-01-10 11:46:29 -060085 ' run time, etc.' + default_string)
Michael Walsh7423c012016-10-04 10:27:21 -050086 elif arg_name == "test_mode":
87 if default is None:
88 default = 0
89 parser.add_argument(
90 '--test_mode',
91 default=default,
92 type=int,
93 choices=[1, 0],
94 help='This means that %(prog)s should go through all the' +
95 ' motions but not actually do anything substantial.' +
96 ' This is mainly to be used by the developer of' +
Michael Walshc33ef372017-01-10 11:46:29 -060097 ' %(prog)s.' + default_string)
Michael Walsh7423c012016-10-04 10:27:21 -050098 elif arg_name == "debug":
99 if default is None:
100 default = 0
101 parser.add_argument(
102 '--debug',
103 default=default,
104 type=int,
105 choices=[1, 0],
106 help='If this parameter is set to "1", %(prog)s will print' +
107 ' additional debug information. This is mainly to be' +
Michael Walshc33ef372017-01-10 11:46:29 -0600108 ' used by the developer of %(prog)s.' + default_string)
Michael Walsh7423c012016-10-04 10:27:21 -0500109 elif arg_name == "loglevel":
110 if default is None:
111 default = "info"
112 parser.add_argument(
113 '--loglevel',
114 default=default,
115 type=str,
116 choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL',
117 'debug', 'info', 'warning', 'error', 'critical'],
118 help='If this parameter is set to "1", %(prog)s will print' +
119 ' additional debug information. This is mainly to be' +
Michael Walshc33ef372017-01-10 11:46:29 -0600120 ' used by the developer of %(prog)s.' + default_string)
Michael Walsh7423c012016-10-04 10:27:21 -0500121
122 arg_obj = parser.parse_args()
123
124 __builtin__.quiet = 0
125 __builtin__.test_mode = 0
126 __builtin__.debug = 0
127 __builtin__.loglevel = 'WARNING'
128 for ix in range(0, len(stock_list)):
129 if type(stock_list[ix]) is tuple:
130 arg_name = stock_list[ix][0]
131 default = stock_list[ix][1]
132 else:
133 arg_name = stock_list[ix]
134 default = None
135 if arg_name == "quiet":
136 __builtin__.quiet = arg_obj.quiet
137 elif arg_name == "test_mode":
138 __builtin__.test_mode = arg_obj.test_mode
139 elif arg_name == "debug":
140 __builtin__.debug = arg_obj.debug
141 elif arg_name == "loglevel":
142 __builtin__.loglevel = arg_obj.loglevel
143
144 __builtin__.arg_obj = arg_obj
145 __builtin__.parser = parser
146
147 # For each command line parameter, create a corresponding global variable
148 # and assign it the appropriate value. For example, if the command line
149 # contained "--last_name='Smith', we'll create a global variable named
150 # "last_name" with the value "Smith".
151 module = sys.modules['__main__']
152 for key in arg_obj.__dict__:
153 setattr(module, key, getattr(__builtin__.arg_obj, key))
154
155 return True
156
157###############################################################################
158
159
Michael Walshc33ef372017-01-10 11:46:29 -0600160###############################################################################
161def set_pgm_arg(var_value,
162 var_name=None):
163
164 r"""
165 Set the value of the arg_obj.__dict__ entry named in var_name with the
166 var_value provided. Also, set corresponding global variable.
167
168 Description of arguments:
169 var_value The value to set in the variable.
170 var_name The name of the variable to set. This
171 defaults to the name of the variable used
172 for var_value when calling this function.
173 """
174
175 if var_name is None:
176 var_name = gp.get_arg_name(None, 1, 2)
177
178 arg_obj.__dict__[var_name] = var_value
179 module = sys.modules['__main__']
180 setattr(module, var_name, var_value)
181 if var_name == "quiet":
182 __builtin__.quiet = var_value
183 elif var_name == "debug":
184 __builtin__.debug = var_value
185 elif var_name == "test_mode":
186 __builtin__.test_mode = var_value
187
188###############################################################################
189
190
Michael Walsh7423c012016-10-04 10:27:21 -0500191# Put this in gen_opt.py or gen_parm.py or gen_arg.py.
192###############################################################################
193def sprint_args(arg_obj,
194 indent=0):
195
196 r"""
197 sprint_var all of the arguments found in arg_obj and return the result as
198 a string.
199
200 Description of arguments:
201 arg_obj An argument object such as is returned by
202 the argparse parse_args() method.
203 indent The number of spaces to indent each line
204 of output.
205 """
206
Michael Walshbec416d2016-11-10 08:54:52 -0600207 loc_col1_width = gp.col1_width + indent
208
Michael Walsh7423c012016-10-04 10:27:21 -0500209 buffer = ""
210
211 for key in arg_obj.__dict__:
Michael Walshbec416d2016-11-10 08:54:52 -0600212 buffer += gp.sprint_varx(key, getattr(arg_obj, key), 0, indent,
213 loc_col1_width)
Michael Walsh7423c012016-10-04 10:27:21 -0500214
215 return buffer
216
217###############################################################################
218
219
220###############################################################################
221def gen_post_validation(exit_function=None,
222 signal_handler=None):
223
224 r"""
225 Do generic post-validation processing. By "post", we mean that this is to
226 be called from a validation function after the caller has done any
227 validation desired. If the calling program passes exit_function and
228 signal_handler parms, this function will register them. In other words,
229 it will make the signal_handler functions get called for SIGINT and
230 SIGTERM and will make the exit_function function run prior to the
231 termination of the program.
232
233 Description of arguments:
234 exit_function A function object pointing to the caller's
235 exit function.
236 signal_handler A function object pointing to the caller's
237 signal_handler function.
238 """
239
240 if exit_function is not None:
241 atexit.register(exit_function)
242 if signal_handler is not None:
243 signal.signal(signal.SIGINT, signal_handler)
244 signal.signal(signal.SIGTERM, signal_handler)
245
246###############################################################################