cmd2.parsing
cmd2.parsing
Statement parsing classes for cmd2
MacroArg
dataclass
Information used to replace or unescape arguments in a macro value when the macro is resolved Normal argument syntax: {5} Escaped argument syntax: {{5}}
macro_normal_arg_pattern
class-attribute
instance-attribute
macro_escaped_arg_pattern
class-attribute
instance-attribute
Macro
dataclass
Statement
dataclass
Statement(
args="",
raw="",
command="",
arg_list=list(),
multiline_command="",
terminator="",
suffix="",
pipe_to="",
output="",
output_to="",
)
Bases: str
String subclass with additional attributes to store the results of parsing.
The cmd module in the standard library passes commands around as a
string. To retain backwards compatibility, cmd2 does the same. However,
we need a place to capture the additional output of the command parsing, so
we add our own attributes to this subclass.
Instances of this class should not be created by anything other than the StatementParser.parse method, nor should any of the attributes be modified once the object is created.
The string portion of the class contains the arguments, but not the command, nor the output redirection clauses.
Tips:
-
argparse <https://docs.python.org/3/library/argparse.html>_ is your friend for anything complex.cmd2has the decorator (cmd2.decorators.with_argparser) which you can use to make your command method receive a namespace of parsed arguments, whether positional or denoted with switches. -
For commands with simple positional arguments, use args or arg_list
-
If you don't want to have to worry about quoted arguments, see argv for a trick which strips quotes off for you.
command_and_args
property
Combine command and args with a space separating them.
Quoted arguments remain quoted. Output redirection and piping are excluded, as are any command terminators.
post_command
property
A string containing any ending terminator, suffix, and redirection chars
argv
property
a list of arguments a-la sys.argv.
The first element of the list is the command after shortcut and macro
expansion. Subsequent elements of the list contain any additional
arguments, with quotes removed, just like bash would. This is very
useful if you are going to use argparse.parse_args().
If you want to strip quotes from the input, you can use argv[1:].
to_dict
Utility method to convert this Statement into a dictionary for use in persistent JSON history files
from_dict
staticmethod
Utility method to restore a Statement from a dictionary
:param source_dict: source data dictionary (generated using to_dict()) :return: Statement object :raises KeyError: if source_dict is missing required elements
| PARAMETER | DESCRIPTION |
|---|---|
source_dict
|
TYPE:
|
Source code in cmd2/parsing.py
StatementParser
Parse user input as a string into discrete command components.
Initialize an instance of StatementParser.
The following will get converted to an immutable tuple before storing internally: terminators, multiline commands, and shortcuts.
:param terminators: iterable containing strings which should terminate commands :param multiline_commands: iterable containing the names of commands that accept multiline input :param aliases: dictionary containing aliases :param shortcuts: dictionary containing shortcuts
| PARAMETER | DESCRIPTION |
|---|---|
terminators
|
TYPE:
|
multiline_commands
|
TYPE:
|
aliases
|
TYPE:
|
shortcuts
|
TYPE:
|
Source code in cmd2/parsing.py
multiline_commands
instance-attribute
multiline_commands = (
tuple(multiline_commands)
if multiline_commands is not None
else ()
)
shortcuts
instance-attribute
is_valid_command
Determine whether a word is a valid name for a command.
Commands cannot include redirection characters, whitespace, or termination characters. They also cannot start with a shortcut.
:param word: the word to check as a command :param is_subcommand: Flag whether this command name is a subcommand name :return: a tuple of a boolean and an error string
If word is not a valid command, return False and an error string
suitable for inclusion in an error message of your choice::
checkit = '>'
valid, errmsg = statement_parser.is_valid_command(checkit)
if not valid:
errmsg = f"alias: {errmsg}"
| PARAMETER | DESCRIPTION |
|---|---|
word
|
TYPE:
|
is_subcommand
|
TYPE:
|
Source code in cmd2/parsing.py
tokenize
Lex a string into a list of tokens. Shortcuts and aliases are expanded and comments are removed.
:param line: the command line being lexed :return: A list of tokens :raises: Cmd2ShlexError if a shlex error occurs (e.g. No closing quotation)
| PARAMETER | DESCRIPTION |
|---|---|
line
|
TYPE:
|
Source code in cmd2/parsing.py
parse
Tokenize the input and parse it into a cmd2.parsing.Statement object, stripping comments, expanding aliases and shortcuts, and extracting output redirection directives.
:param line: the command line being parsed :return: a new cmd2.parsing.Statement object :raises: Cmd2ShlexError if a shlex error occurs (e.g. No closing quotation)
| PARAMETER | DESCRIPTION |
|---|---|
line
|
TYPE:
|
Source code in cmd2/parsing.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 | |
parse_command_only
Partially parse input into a cmd2.Statement object.
The command is identified, and shortcuts and aliases are expanded. Multiline commands are identified, but terminators and output redirection are not parsed.
This method is used by tab completion code and therefore must not generate an exception if there are unclosed quotes.
The cmd2.parsing.Statement object returned by this method can at most contain values in the following attributes: cmd2.parsing.Statement.args, cmd2.parsing.Statement.raw, cmd2.parsing.Statement.command, cmd2.parsing.Statement.multiline_command
cmd2.parsing.Statement.args will include all output redirection clauses and command terminators.
Different from cmd2.parsing.StatementParser.parse this method does not remove redundant whitespace within args. However, it does ensure args has no leading or trailing whitespace.
:param rawinput: the command line as entered by the user :return: a new cmd2.Statement object
| PARAMETER | DESCRIPTION |
|---|---|
rawinput
|
TYPE:
|
Source code in cmd2/parsing.py
get_command_arg_list
Convenience method used by the argument parsing decorators.
Retrieves just the arguments being passed to their do_* methods as a list.
:param command_name: name of the command being run
:param to_parse: what is being passed to the do_* method. It can be one of two types:
1. An already parsed [cmd2.Statement][]
2. An argument string in cases where a ``do_*`` method is
explicitly called. Calling ``do_help('alias create')`` would
cause ``to_parse`` to be 'alias create'.
In this case, the string will be converted to a
[cmd2.Statement][] and returned along with
the argument list.
:param preserve_quotes: if True, then quotes will not be stripped from
the arguments
:return: A tuple containing the cmd2.Statement and a list of
strings representing the arguments
| PARAMETER | DESCRIPTION |
|---|---|
command_name
|
TYPE:
|
to_parse
|
TYPE:
|
preserve_quotes
|
TYPE:
|
Source code in cmd2/parsing.py
split_on_punctuation
Further splits tokens from a command line using punctuation characters.
Punctuation characters are treated as word breaks when they are in unquoted strings. Each run of punctuation characters is treated as a single token.
:param tokens: the tokens as parsed by shlex :return: a new list of tokens, further split using punctuation
| PARAMETER | DESCRIPTION |
|---|---|
tokens
|
TYPE:
|
Source code in cmd2/parsing.py
shlex_split
A wrapper around shlex.split() that uses cmd2's preferred arguments. This allows other classes to easily call split() the same way StatementParser does.
:param str_to_split: the string being split :return: A list of tokens
| PARAMETER | DESCRIPTION |
|---|---|
str_to_split
|
TYPE:
|