Back to index

python3.2  3.2.2
Classes | Functions | Variables
getopt Namespace Reference

Classes

class  GetoptError

Functions

def getopt
def gnu_getopt
def do_longs
def long_has_args
def do_shorts
def short_has_arg

Variables

list __all__ = ["GetoptError","error","getopt","gnu_getopt"]
 error = GetoptError

Detailed Description

Parser for command line options.

This module helps scripts to parse the command line arguments in
sys.argv.  It supports the same conventions as the Unix getopt()
function (including the special meanings of arguments of the form `-'
and `--').  Long options similar to those supported by GNU software
may be used as well via an optional third argument.  This module
provides two functions and an exception:

getopt() -- Parse command line options
gnu_getopt() -- Like getopt(), but allow option and non-option arguments
to be intermixed.
GetoptError -- exception (class) raised with 'opt' attribute, which is the
option involved with the exception.

Function Documentation

def getopt.do_longs (   opts,
  opt,
  longopts,
  args 
)

Definition at line 144 of file getopt.py.

00144 
00145 def do_longs(opts, opt, longopts, args):
00146     try:
00147         i = opt.index('=')
00148     except ValueError:
00149         optarg = None
00150     else:
00151         opt, optarg = opt[:i], opt[i+1:]
00152 
00153     has_arg, opt = long_has_args(opt, longopts)
00154     if has_arg:
00155         if optarg is None:
00156             if not args:
00157                 raise GetoptError('option --%s requires argument' % opt, opt)
00158             optarg, args = args[0], args[1:]
00159     elif optarg is not None:
00160         raise GetoptError('option --%s must not have an argument' % opt, opt)
00161     opts.append(('--' + opt, optarg or ''))
00162     return opts, args
00163 
00164 # Return:
00165 #   has_arg?
#   full option name

Here is the call graph for this function:

Here is the caller graph for this function:

def getopt.do_shorts (   opts,
  optstring,
  shortopts,
  args 
)

Definition at line 187 of file getopt.py.

00187 
00188 def do_shorts(opts, optstring, shortopts, args):
00189     while optstring != '':
00190         opt, optstring = optstring[0], optstring[1:]
00191         if short_has_arg(opt, shortopts):
00192             if optstring == '':
00193                 if not args:
00194                     raise GetoptError('option -%s requires argument' % opt,
00195                                       opt)
00196                 optstring, args = args[0], args[1:]
00197             optarg, optstring = optstring, ''
00198         else:
00199             optarg = ''
00200         opts.append(('-' + opt, optarg))
00201     return opts, args

Here is the call graph for this function:

Here is the caller graph for this function:

def getopt.getopt (   args,
  shortopts,
  longopts = [] 
)
getopt(args, options[, long_options]) -> opts, args

Parses command line options and parameter list.  args is the
argument list to be parsed, without the leading reference to the
running program.  Typically, this means "sys.argv[1:]".  shortopts
is the string of option letters that the script wants to
recognize, with options that require an argument followed by a
colon (i.e., the same format that Unix getopt() uses).  If
specified, longopts is a list of strings with the names of the
long options which should be supported.  The leading '--'
characters should not be included in the option name.  Options
which require an argument should be followed by an equal sign
('=').

The return value consists of two elements: the first is a list of
(option, value) pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice
of the first argument).  Each option-and-value pair returned has
the option as its first element, prefixed with a hyphen (e.g.,
'-x'), and the option argument as its second element, or an empty
string if the option has no argument.  The options occur in the
list in the same order in which they were found, thus allowing
multiple occurrences.  Long and short options may be mixed.

Definition at line 51 of file getopt.py.

00051 
00052 def getopt(args, shortopts, longopts = []):
00053     """getopt(args, options[, long_options]) -> opts, args
00054 
00055     Parses command line options and parameter list.  args is the
00056     argument list to be parsed, without the leading reference to the
00057     running program.  Typically, this means "sys.argv[1:]".  shortopts
00058     is the string of option letters that the script wants to
00059     recognize, with options that require an argument followed by a
00060     colon (i.e., the same format that Unix getopt() uses).  If
00061     specified, longopts is a list of strings with the names of the
00062     long options which should be supported.  The leading '--'
00063     characters should not be included in the option name.  Options
00064     which require an argument should be followed by an equal sign
00065     ('=').
00066 
00067     The return value consists of two elements: the first is a list of
00068     (option, value) pairs; the second is the list of program arguments
00069     left after the option list was stripped (this is a trailing slice
00070     of the first argument).  Each option-and-value pair returned has
00071     the option as its first element, prefixed with a hyphen (e.g.,
00072     '-x'), and the option argument as its second element, or an empty
00073     string if the option has no argument.  The options occur in the
00074     list in the same order in which they were found, thus allowing
00075     multiple occurrences.  Long and short options may be mixed.
00076 
00077     """
00078 
00079     opts = []
00080     if type(longopts) == type(""):
00081         longopts = [longopts]
00082     else:
00083         longopts = list(longopts)
00084     while args and args[0].startswith('-') and args[0] != '-':
00085         if args[0] == '--':
00086             args = args[1:]
00087             break
00088         if args[0].startswith('--'):
00089             opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
00090         else:
00091             opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
00092 
00093     return opts, args

Here is the call graph for this function:

def getopt.gnu_getopt (   args,
  shortopts,
  longopts = [] 
)
getopt(args, options[, long_options]) -> opts, args

This function works like getopt(), except that GNU style scanning
mode is used by default. This means that option and non-option
arguments may be intermixed. The getopt() function stops
processing options as soon as a non-option argument is
encountered.

If the first character of the option string is `+', or if the
environment variable POSIXLY_CORRECT is set, then option
processing stops as soon as a non-option argument is encountered.

Definition at line 94 of file getopt.py.

00094 
00095 def gnu_getopt(args, shortopts, longopts = []):
00096     """getopt(args, options[, long_options]) -> opts, args
00097 
00098     This function works like getopt(), except that GNU style scanning
00099     mode is used by default. This means that option and non-option
00100     arguments may be intermixed. The getopt() function stops
00101     processing options as soon as a non-option argument is
00102     encountered.
00103 
00104     If the first character of the option string is `+', or if the
00105     environment variable POSIXLY_CORRECT is set, then option
00106     processing stops as soon as a non-option argument is encountered.
00107 
00108     """
00109 
00110     opts = []
00111     prog_args = []
00112     if isinstance(longopts, str):
00113         longopts = [longopts]
00114     else:
00115         longopts = list(longopts)
00116 
00117     # Allow options after non-option arguments?
00118     if shortopts.startswith('+'):
00119         shortopts = shortopts[1:]
00120         all_options_first = True
00121     elif os.environ.get("POSIXLY_CORRECT"):
00122         all_options_first = True
00123     else:
00124         all_options_first = False
00125 
00126     while args:
00127         if args[0] == '--':
00128             prog_args += args[1:]
00129             break
00130 
00131         if args[0][:2] == '--':
00132             opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
00133         elif args[0][:1] == '-' and args[0] != '-':
00134             opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
00135         else:
00136             if all_options_first:
00137                 prog_args += args
00138                 break
00139             else:
00140                 prog_args.append(args[0])
00141                 args = args[1:]
00142 
00143     return opts, prog_args

Here is the call graph for this function:

Here is the caller graph for this function:

def getopt.long_has_args (   opt,
  longopts 
)

Definition at line 166 of file getopt.py.

00166 
00167 def long_has_args(opt, longopts):
00168     possibilities = [o for o in longopts if o.startswith(opt)]
00169     if not possibilities:
00170         raise GetoptError('option --%s not recognized' % opt, opt)
00171     # Is there an exact match?
00172     if opt in possibilities:
00173         return False, opt
00174     elif opt + '=' in possibilities:
00175         return True, opt
00176     # No exact match, so better be unique.
00177     if len(possibilities) > 1:
00178         # XXX since possibilities contains all valid continuations, might be
00179         # nice to work them into the error msg
00180         raise GetoptError('option --%s not a unique prefix' % opt, opt)
00181     assert len(possibilities) == 1
00182     unique_match = possibilities[0]
00183     has_arg = unique_match.endswith('=')
00184     if has_arg:
00185         unique_match = unique_match[:-1]
00186     return has_arg, unique_match

Here is the caller graph for this function:

def getopt.short_has_arg (   opt,
  shortopts 
)

Definition at line 202 of file getopt.py.

00202 
00203 def short_has_arg(opt, shortopts):
00204     for i in range(len(shortopts)):
00205         if opt == shortopts[i] != ':':
00206             return shortopts.startswith(':', i+1)
00207     raise GetoptError('option -%s not recognized' % opt, opt)

Here is the caller graph for this function:


Variable Documentation

list getopt.__all__ = ["GetoptError","error","getopt","gnu_getopt"]

Definition at line 34 of file getopt.py.

Definition at line 49 of file getopt.py.