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: Any, **kwargs: Any)¶
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.在 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
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.在 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) 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', ...])
- 参数:
argv – List of argument string tokens.
- 返回:
A
ParseResult(alistsubclass containing some number ofParserContextobjects).
在 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
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.
- __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 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.
在 1.0 版本加入.
- property as_kwargs: Dict[str, Any]¶
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.在 1.0 版本加入.
- flag_names() Tuple[str, ...]¶
Similar to
help_tuplesbut 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 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.
在 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 aslistkinds, 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 innamesotherwise.在 1.0 版本加入.
- set_value(value: Any, cast: bool = True) None¶
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.
在 1.0 版本加入.