parser¶
The command-line parsing framework is split up into a handful of sub-modules:
parser.argumentparser.context(not to be confused with the top levelcontext!)parser.parser
API docs for all are below.
-
class
invoke.parser.parser.ParseResult(*args, **kwargs)¶ List-like object with some extra parse-related attributes.
Specifically, a
.remainderattribute, which is the string found after a--in any parsed argv list; and an.unparsedattribute, a list of tokens that were unable to be parsed.New in version 1.0.
-
__init__(*args, **kwargs)¶ x.__init__(…) initializes x; see help(type(x)) for signature
-
__weakref__¶ list of weak references to the object (if defined)
-
-
class
invoke.parser.parser.Parser(contexts=(), initial=None, ignore_unknown=False)¶ Create parser conscious of
contextsand optionalinitialcontext.contextsshould be an iterable ofContextinstances which will be searched when new context names are encountered during a parse. These Contexts determine what flags may follow them, as well as whether given flags take values.initialis optional and will be used to determine validity of “core” options/flags at the start of the parse run, if any are encountered.ignore_unknowndetermines what to do when contexts are found which do not map to any members ofcontexts. By default it isFalse, meaning any unknown contexts result in a parse error exception. IfTrue, encountering an unknown context halts parsing and populates the return value’s.unparsedattribute with the remaining parse tokens.New in version 1.0.
-
__init__(contexts=(), initial=None, ignore_unknown=False)¶ x.__init__(…) initializes x; see help(type(x)) for signature
-
__weakref__¶ list of weak references to the object (if defined)
-
parse_argv(argv)¶ Parse an argv-style token list
argv.Returns a list (actually a subclass,
ParseResult) ofParserContextobjects matching the order they were found in theargvand containingArgumentobjects with updated values based on any flags given.Assumes any program name has already been stripped out. Good:
Parser(...).parse_argv(['--core-opt', 'task', '--task-opt'])
Bad:
Parser(...).parse_argv(['invoke', '--core-opt', ...])
Parameters: argv – List of argument string tokens. Returns: A ParseResult(alistsubclass containing some number ofParserContextobjects).New in version 1.0.
-
-
class
invoke.parser.context.ParserContext(name=None, aliases=(), args=())¶ Parsing context with knowledge of flags & their format.
Generally associated with the core program or a task.
When run through a parser, will also hold runtime values filled in by the parser.
New in version 1.0.
-
__init__(name=None, aliases=(), args=())¶ Create a new
ParserContextnamedname, withaliases.nameis optional, and should be a string if given. It’s used to tell ParserContext objects apart, and for use in a Parser when determining what chunk of input might belong to a given ParserContext.aliasesis also optional and should be an iterable containing strings. Parsing will honor any aliases when trying to “find” a given context in its input.May give one or more
args, which is a quick alternative to callingfor arg in args: self.add_arg(arg)after initialization.
-
__repr__() <==> repr(x)¶
-
__weakref__¶ list of weak references to the object (if defined)
-
add_arg(*args, **kwargs)¶ Adds given
Argument(or constructor args for one) to this context.The Argument in question is added to the following dict attributes:
args: “normal” access, i.e. the given names are directly exposed as keys.flags: “flaglike” access, i.e. the given names are translated into CLI flags, e.g."foo"is accessible viaflags['--foo'].inverse_flags: similar toflagsbut containing only the “inverse” versions of boolean flags which default to True. This allows the parser to track e.g.--no-myflagand turn it into a False value for themyflagArgument.
New in version 1.0.
-
as_kwargs¶ This context’s arguments’ values keyed by their
.nameattribute.Results in a dict suitable for use in Python contexts, where e.g. an arg named
foo-barbecomes accessible asfoo_bar.New in version 1.0.
-
flag_names()¶ Similar to
help_tuplesbut returns flag names only, no helpstrs.Specifically, all flag names, flattened, in rough order.
New in version 1.0.
-
help_for(flag)¶ Return 2-tuple of
(flag-spec, help-string)for givenflag.New in version 1.0.
-
help_tuples()¶ Return sorted iterable of help tuples for all member Arguments.
Sorts like so:
- General sort is alphanumerically
- Short flags win over long flags
- Arguments with only long flags and no short flags will come first.
- When an Argument has multiple long or short flags, it will sort using the most favorable (lowest alphabetically) candidate.
This will result in a help list like so:
--alpha, --zeta # 'alpha' wins --beta -a, --query # short flag wins -b, --argh -c
New in version 1.0.
-
-
invoke.parser.context.flag_key(x)¶ Obtain useful key list-of-ints for sorting CLI flags.
New in version 1.0.
-
class
invoke.parser.argument.Argument(name=None, names=(), kind=<type 'str'>, default=None, help=None, positional=False, optional=False, incrementable=False, attr_name=None)¶ A command-line argument/flag.
Parameters: - name – Syntactic sugar for
names=[<name>]. Giving bothnameandnamesis invalid. - names – List of valid identifiers for this argument. For example, a “help”
argument may be defined with a name list of
['-h', '--help']. - kind – Type factory & parser hint. E.g.
intwill turn the default text value parsed, into a Python integer; andboolwill tell the parser not to expect an actual value but to treat the argument as a toggle/flag. - default – Default value made available to the parser if no value is given on the command line.
- help – Help text, intended for use with
--help. - positional – Whether or not this argument’s value may be given positionally. When
False(default) arguments must be explicitly named. - optional – Whether or not this (non-
bool) argument requires a value. - incrementable – Whether or not this (
int) argument is to be incremented instead of overwritten/assigned to. - attr_name – A Python identifier/attribute friendly name, typically filled in with
the underscored version when
name/namescontain dashes.
New in version 1.0.
-
__init__(name=None, names=(), kind=<type 'str'>, default=None, help=None, positional=False, optional=False, incrementable=False, attr_name=None)¶ x.__init__(…) initializes x; see help(type(x)) for signature
-
__repr__() <==> repr(x)¶
-
__weakref__¶ list of weak references to the object (if defined)
-
got_value¶ Returns whether the argument was ever given a (non-default) value.
For most argument kinds, this simply checks whether the internally stored value is non-
None; for others, such aslistkinds, different checks may be used.New in version 1.3.
-
name¶ The canonical attribute-friendly name for this argument.
Will be
attr_name(if given to constructor) or the first name innamesotherwise.New in version 1.0.
-
set_value(value, cast=True)¶ Actual explicit value-setting API call.
Sets
self.raw_valuetovaluedirectly.Sets
self.valuetoself.kind(value), unless:cast=False, in which case the raw value is also used.self.kind==list, in which case the value is appended toself.valueinstead of cast & overwritten.self.incrementable==True, in which case the value is ignored and the current (assumed int) value is simply incremented.
New in version 1.0.
- name – Syntactic sugar for