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 levelcontext
!)parser.parser
API docs for all are below.
- class invoke.parser.parser.ParseResult(*args: Any, **kwargs: Any)¶
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.在 1.0 版本加入.
- __weakref__¶
list of weak references to the object
- class invoke.parser.parser.Parser(contexts: Iterable[ParserContext] = (), initial: ParserContext | None = None, ignore_unknown: bool = False)¶
Create parser conscious of
contexts
and optionalinitial
context.contexts
should be an iterable ofContext
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 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.unparsed
attribute with the remaining parse tokens.在 1.0 版本加入.
- __init__(contexts: Iterable[ParserContext] = (), initial: ParserContext | None = None, ignore_unknown: bool = False) None ¶
- parse_argv(argv: List[str]) ParseResult ¶
Parse an argv-style token list
argv
.Returns a list (actually a subclass,
ParseResult
) ofParserContext
objects matching the order they were found in theargv
and containingArgument
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', ...])
- 参数:
argv – List of argument string tokens.
- 返回:
A
ParseResult
(alist
subclass containing some number ofParserContext
objects).
在 1.0 版本加入.
- __weakref__¶
list of weak references to the object
- class invoke.parser.context.ParserContext(name: str | None = None, aliases: Iterable[str] = (), args: Iterable[Argument] = ())¶
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.
在 1.0 版本加入.
- __init__(name: str | None = None, aliases: Iterable[str] = (), args: Iterable[Argument] = ()) None ¶
Create a new
ParserContext
namedname
, withaliases
.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 callingfor arg in args: self.add_arg(arg)
after initialization.
- __weakref__¶
list of weak references to the object
- add_arg(*args: Any, **kwargs: Any) None ¶
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 toflags
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 themyflag
Argument.
在 1.0 版本加入.
- property as_kwargs: Dict[str, Any]¶
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 asfoo_bar
.在 1.0 版本加入.
- flag_names() Tuple[str, ...] ¶
Similar to
help_tuples
but returns flag names only, no helpstrs.Specifically, all flag names, flattened, in rough order.
在 1.0 版本加入.
- help_for(flag: str) Tuple[str, str] ¶
Return 2-tuple of
(flag-spec, help-string)
for givenflag
.在 1.0 版本加入.
- help_tuples() List[Tuple[str, str | None]] ¶
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
在 1.0 版本加入.
- invoke.parser.context.flag_key(arg: Argument) List[str | int] ¶
Obtain useful key list-of-ints for sorting CLI flags.
在 1.0 版本加入.
- class invoke.parser.argument.Argument(name: str | None = None, names: ~typing.Iterable[str] = (), kind: ~typing.Any = <class 'str'>, default: ~typing.Any | None = None, help: str | None = None, positional: bool = False, optional: bool = False, incrementable: bool = False, attr_name: str | None = None)¶
A command-line argument/flag.
- 参数:
name – Syntactic sugar for
names=[<name>]
. Giving bothname
andnames
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; andbool
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.
在 1.0 版本加入.
- __init__(name: str | None = None, names: ~typing.Iterable[str] = (), kind: ~typing.Any = <class 'str'>, default: ~typing.Any | None = None, help: str | None = None, positional: bool = False, optional: bool = False, incrementable: bool = False, attr_name: str | None = None) None ¶
- __weakref__¶
list of weak references to the object
- property got_value: bool¶
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 aslist
kinds, different checks may be used.在 1.3 版本加入.
- property name: str | None¶
The canonical attribute-friendly name for this argument.
Will be
attr_name
(if given to constructor) or the first name innames
otherwise.在 1.0 版本加入.
- set_value(value: Any, cast: bool = True) None ¶
Actual explicit value-setting API call.
Sets
self.raw_value
tovalue
directly.Sets
self.value
toself.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.value
instead of cast & overwritten.self.incrementable==True
, in which case the value is ignored and the current (assumed int) value is simply incremented.
在 1.0 版本加入.