Parsing Options
Clap comes with its own powerful and flexible option parser.
Defining Options
Options are defined using the Option class.
-
class clap.parser.Option(short=None, long=None, argument=False, target=None, type=None, constant=True, desc='')
This class represent a single option. If you improperly define any of
these parameters, an OptionDefError will be raised.
Parameters: |
- short – The short form of the option. This should be a single letter
in the range A-Za-z0-9?. It can also be None, in
which case there is no short form.
- long – The long form of the option. This should be a word consisting
of characters in the range A-Za-z0-9-. It can also be
None, in which case there is no long form. (You must
have either a short or a long form. Otherwise it makes no
sense.)
- argument – Whether the option takes an argument. It can be
True (argument is required) or False
(argument is forbidden). There are no optional arguments.
- target – If given, this is the key in the options dict this will be
stored in. If not given, it defaults to the long form, with
dashes replaced with underscores.
- type – If given, this is used to convert the option argument to a
value from a string. It should be a callable that returns a
value (like int), but if it raises a
ValueError, an OptionArgumentInvalid error
will be raised. If this is given, argument is implied
to be True.
- constant – The value that is used for the option’s value if an
argument is not given. It defaults to True.
- desc – A brief description of an option. This should preferably
start with a capital letter, not end in punctuation, and be
< 50 characters.
|
Here are a few example options:
Option('v', 'verbose', desc='Prints extra output')
Option('o', 'output', argument=True, desc='Write output to a file '
'instead of stdout')
Option('t', 'timeout', type=int, desc='Timeout for HTTP requests')
Option(long='ignore-checksum', desc='Don\'t compute checksums of files '
'to ensure integrity')
Parsing Options
The preferred way to parse options is with the parse() function.
-
clap.parser.parse(optiondefs, argv=None, defaults=None, interspersed_options=True, callback=None, parser_cls=<class 'clap.parser.OptionParser'>)
This will parse the arguments. It is preferred to use this instead of
OptionParser directly because it handles the parser’s lifecycle
behind the scenes.
It returns a 2-tuple. The first item is a dictionary, that maps option
names to values. The second item is a list, of the positional arguments
captured.
Everything besides optiondefs and argv should be passed as
keyword arguments in case the option order is changed later.
Parameters: |
- optiondefs – A list of Option instances.
- argv – The arguments to actually parse. If not given, they default
to sys.argv[1:].
- defaults – A dictionary of default values. If given, the option
values dict will be updated with them before parsing.
- interspersed_options – If this is False, once the first
non-option argument is encountered, the
parser will treat everything following as a
regular positional argument. The default is
True.
- callback – If this is given, it should take the
OptionParser instance, the Option
instance, and the captured value (if any). If it returns
None, the value will be saved as normal. If it
returns anything else, it will not.
- parser_cls – The parser class to use. It defaults to
OptionParser.
|
However, if you need more control over the parsing process, you may want to
create an OptionParser yourself.
-
class clap.parser.OptionParser(optiondefs, interspersed_options=True, callback=None)
This class actually does something with its options. Initialize it with
the option definitions and a few other keyword arguments, call
parse(), and then access arguments and option_values
for the positional arguments and option values, respectively.
However, it’s best not to use instances of this class directly. They are
not reusable - once you parse some arguments, the parser has too much
leftover state to parse again. The best way to use it is with the
parse() function.
Parameters: |
- optiondefs – An iterable of Option instances.
- interspersed_options – If this is False, once the first
non-option argument is encountered, the
parser will treat everything following as a
regular positional argument. The default is
True.
- callback – If this is given, it should take the
OptionParser instance, the Option
instance, and the captured value (if any). If it returns
None, the value will be saved as normal. If it
returns anything else, it will not.
|
-
arguments
- Once parse() is called, this will be a list of the positional
arguments that were parsed.
-
option_values
- Once parse() is called, this will be a dictionary of values from
all the options that were parsed.
-
parse(argv)
This will parse the given arguments. Please note that each
Parser is only good for one set of arguments, and you should
destroy it and create a new one if you need to parse a new set of
arguments. If not, it will raise a RuntimeError when you
call parse() again.
Parameter: | argv – The arguments to parse. This does NOT default to
sys.argv. |
-
set_defaults(defaults)
This updates the option_values dictionary with the given
defaults.
Parameter: | defaults – The values to update the option values with. |
Remember that since OptionParser.parse() only invokes the parser loop
and doesn’t return anything, you will need to access the arguments and
option_values attributes yourself.
Option Parsing Exceptions
All exceptions inherit from the OptionError class.
-
exception clap.parser.OptionError
Bases: exceptions.Exception
This is the base class for all exceptions thrown by the option parser.
If you define an option that doesn’t work (for example, you give neither a
long form nor a short form), a OptionDefError will be raised.
-
exception clap.parser.OptionDefError
Bases: clap.parser.OptionError
This error is raised when an option was given an invalid definition.
While actually parsing options, these exceptions may be raised:
-
exception clap.parser.OptionParsingError(option)
Bases: clap.parser.OptionError
These errors can be raised during parsing and indicate that something is
wrong with the provided arguments.
-
exception clap.parser.DoesNotTakeArgument(option)
Bases: clap.parser.OptionParsingError
This indicates that the given option does not take an argument.
-
exception clap.parser.ArgumentRequired(option)
Bases: clap.parser.OptionParsingError
This indicates that the given option does take an argument, but one was
not found.
-
exception clap.parser.IllegalOption(option)
Bases: clap.parser.OptionParsingError
This indicates that the given option does not exist.