parser

The command-line parsing framework is split up into a handful of sub-modules:

  • parser.argument
  • parser.context (not to be confused with the top level context!)
  • 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 .remainder attribute, which is the string found after a -- in any parsed argv list; and an .unparsed attribute, a list of tokens that were unable to be parsed.

New in version 1.0.

__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 contexts and optional initial context.

contexts should be an iterable of Context instances 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.

initial is optional and will be used to determine validity of “core” options/flags at the start of the parse run, if any are encountered.

ignore_unknown determines what to do when contexts are found which do not map to any members of contexts. By default it is False, meaning any unknown contexts result in a parse error exception. If True, encountering an unknown context halts parsing and populates the return value’s .unparsed attribute with the remaining parse tokens.

New in version 1.0.

__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) of ParserContext objects matching the order they were found in the argv and containing Argument objects 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 (a list subclass containing some number of ParserContext objects).

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 ParserContext named name, with aliases.

name is 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.

aliases is 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 calling for arg in args: self.add_arg(arg) after initialization.

__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 via flags['--foo'].
  • inverse_flags: similar to flags but containing only the “inverse” versions of boolean flags which default to True. This allows the parser to track e.g. --no-myflag and turn it into a False value for the myflag Argument.

New in version 1.0.

as_kwargs

This context’s arguments’ values keyed by their .name attribute.

Results in a dict suitable for use in Python contexts, where e.g. an arg named foo-bar becomes accessible as foo_bar.

New in version 1.0.

flag_names()

Similar to help_tuples but 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 given flag.

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 both name and names is 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. int will turn the default text value parsed, into a Python integer; and bool will 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/names contain dashes.

New in version 1.0.

__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 as list kinds, 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 in names otherwise.

New in version 1.0.

set_value(value, cast=True)

Actual explicit value-setting API call.

Sets self.raw_value to value directly.

Sets self.value to self.kind(value), unless:

  • cast=False, in which case the raw value is also used.
  • self.kind==list, in which case the value is appended to self.value instead 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.