blob: c34d1849dd00917a6092ab81aecf5dbe5dc995a0 [file] [log] [blame]
Deepak Panickal9b35cf52014-07-01 17:57:19 +00001""" Utility module handle program args and give help
2
3 --------------------------------------------------------------------------
4 File: utilsArgsParse.py
5
6 Overview: Python module to parse and validate program parameters
7 against those required by the program whether mandatory
8 or optional.
9 Also give help information on arguments required by the
10 program.
11
12 Environment: OS: Windows/LINUX/OSX
13 IDE: Visual Studio 2013 Plugin Python Tools (PTVS)
14 Script: Python 2.6 x64
15
16 Gotchas: None.
17
18 Copyright: None.
19 --------------------------------------------------------------------------
20
21"""
22
23# Python modules:
24import sys # Provide argument parsing
25import getopt # Parse command line arguments
26
27# Third party modules:
28
29# In-house modules:
30import utilsOsType # Determine the OS type this script is running on
31
32# Instantiations:
33
34# User facing text:
35strMsgErrorInvalidParameters = "Invalid parameters entered, -h for help. \nYou entered:\n";
36strMsgErrorInvalidNoParams = "No parameters entered, -h for help\n";
37strMsgErrorNumberParameters = "Number of parameters entered incorrect, %d parameters required. You entered:\n";
38strMsgArgFileNotImplemented = "Sorry the --argFile is not implemented";
39
40#++---------------------------------------------------------------------------
41# Details: Validate the arguments passed in against the mandatory and
42# optional arguments specified. The argument format for the parameters
43# is required to work with the module getopt function getopt().
44# Parameter vDictArgReq specifies which parameters are mandatory and
45# which are optional. The format is for example:
46# dictArgReq = { "-h": "o", # o = optional, m = mandatory
47# "-m": "m",
48# "--targetDir": "m",
49# "--cfgBldDir": "o" };
50# Args: vArgv - (R) List of arguments and values.
51# vstrListArgs - (R) List of small arguments.
52# vListLongArgs - (R) List of long arguments.
53# vDictArgReq - (R) Map of arguments required.
54# vstrHelpInfo - (R) Formatted help text.
55# Returns: Int - 0 success.
56# 1 success display information, do nothing else.
57# -1 error invalid parameters.
58# -2 error incorrect number of mandatory parameters.
59# Dict - Map of arguments names to argument values
60# Str - Error message.
61# Throws: None.
62#--
63def parse( vArgv, vstrListArgs, vListLongArgs, vDictArgReq, vstrHelpInfo ):
64 dictArgs = {};
65 dictDummy = {};
66 strDummy = "";
67
68 # Validate parameters above and error on not recognised
69 try:
70 dictOptsNeeded, dictArgsLeftOver = getopt.getopt( vArgv,
71 vstrListArgs,
72 vListLongArgs );
73 except getopt.GetoptError:
74 strMsg = strMsgErrorInvalidParameters;
75 strMsg += str( vArgv );
76 return (-1, dictDummy, strMsg);
77
78 if len( dictOptsNeeded ) == 0:
79 strMsg = strMsgErrorInvalidNoParams;
80 return (-1, dictDummy, strMsg);
81
82 # Look for help -h before anything else
83 for opt, arg in dictOptsNeeded:
84 if opt == '-h':
85 return (1, dictDummy, vstrHelpInfo );
86
87 # Look for the --argFile if found ignore other command line arguments
88 for opt, arg in dictOptsNeeded:
89 if opt == '--argsFile':
90 return (1, dictDummy, strMsgArgFileNotImplemented);
91
92 # Count the number of mandatory args required (if any one found)
93 countMandatory = 0;
94 for opt, man in vDictArgReq.iteritems():
95 if man == "m":
96 countMandatory = countMandatory + 1;
97
98 # Extract short args
99 listArgs = [];
100 for arg in vstrListArgs:
101 if (arg == '-h') or (arg == ':'):
102 continue;
103 listArgs.append( arg );
104
105 # Append to arg dictionary the option and its value
106 bFoundNoInputValue = False;
107 countMandatoryOpts = 0;
108 for opt, val in dictOptsNeeded:
109 match = 0;
110 for arg in listArgs:
111 argg = "-" + arg;
112 if opt == argg:
113 if "m" == vDictArgReq[ opt ]:
114 countMandatoryOpts = countMandatoryOpts + 1;
115 dictArgs[ opt ] = val;
116 match = 1;
117 break;
118 if match == 0:
119 for arg in vListLongArgs:
120 argg = "--" + arg[:arg.__len__() - 1];
121 if opt == argg:
122 if "m" == vDictArgReq[ opt ]:
123 countMandatoryOpts = countMandatoryOpts + 1;
124 dictArgs[ opt ] = val;
125 if val.__len__() == 0:
126 bFoundNoInputValue = True;
127 break;
128
129 # Do any of the long arguments not have a value attached
130 if bFoundNoInputValue:
131 strMsg = strMsgErrorInvalidParameters;
132 strMsg += str( vArgv );
133 return (-1, dictDummy, strMsg);
134
135 # Debug only
136 #print countMandatoryOpts
137 #print countMandatory
138
139 # Do we have the exact number of mandatory arguments
140 if (countMandatoryOpts > 0) and (countMandatory != countMandatoryOpts):
141 strMsg = strMsgErrorNumberParameters % countMandatory;
142 strMsg += str( vArgv );
143 return (-2, dictDummy, strMsg);
144
145 return (0, dictArgs, strDummy);
146