cmd2.Cmd
cmd2.Cmd
Cmd(completekey='tab', stdin=None, stdout=None, *, persistent_history_file='', persistent_history_length=1000, startup_script='', silence_startup_script=False, include_py=False, include_ipy=False, allow_cli_args=True, transcript_files=None, allow_redirection=True, multiline_commands=None, terminators=None, shortcuts=None, command_sets=None, auto_load_commands=True, allow_clipboard=True, suggest_similar_command=False)
Bases: Cmd
An easy but powerful framework for writing line-oriented command interpreters.
Extends the Python Standard Library’s cmd package by adding a lot of useful features to the out of the box configuration.
Line-oriented command interpreters are often useful for test harnesses, internal tools, and rapid prototypes.
An easy but powerful framework for writing line-oriented command interpreters. Extends Python's cmd package.
PARAMETER | DESCRIPTION |
---|---|
completekey
|
readline name of a completion key, default to Tab
TYPE:
|
stdin
|
alternate input file object, if not specified, sys.stdin is used
TYPE:
|
stdout
|
alternate output file object, if not specified, sys.stdout is used
TYPE:
|
persistent_history_file
|
file path to load a persistent cmd2 command history from
TYPE:
|
persistent_history_length
|
max number of history items to write to the persistent history file
TYPE:
|
startup_script
|
file path to a script to execute at startup
TYPE:
|
silence_startup_script
|
if
TYPE:
|
include_py
|
should the "py" command be included for an embedded Python shell
TYPE:
|
include_ipy
|
should the "ipy" command be included for an embedded IPython shell
TYPE:
|
allow_cli_args
|
if
TYPE:
|
transcript_files
|
pass a list of transcript files to be run on initialization. This allows running transcript tests when
TYPE:
|
allow_redirection
|
If
TYPE:
|
multiline_commands
|
list of commands allowed to accept multi-line input
TYPE:
|
terminators
|
list of characters that terminate a command. These are mainly intended for terminating multiline commands, but will also terminate single-line commands. If not supplied, the default is a semicolon. If your app only contains single-line commands and you want terminators to be treated as literals by the parser, then set this to an empty list.
TYPE:
|
shortcuts
|
dictionary containing shortcuts for commands. If not supplied, then defaults to constants.DEFAULT_SHORTCUTS. If you do not want any shortcuts, pass an empty dictionary.
TYPE:
|
command_sets
|
Provide CommandSet instances to load during cmd2 initialization. This allows CommandSets with custom constructor parameters to be loaded. This also allows the a set of CommandSets to be provided when
TYPE:
|
auto_load_commands
|
If True, cmd2 will check for all subclasses of
TYPE:
|
allow_clipboard
|
If False, cmd2 will disable clipboard interactions
TYPE:
|
suggest_similar_command
|
If
TYPE:
|
Source code in cmd2/cmd2.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 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 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 |
|
INTERNAL_COMMAND_EPILOG
class-attribute
instance-attribute
INTERNAL_COMMAND_EPILOG = 'Notes:\n This command is for internal use and is not intended to be called from the\n command line.'
statement_parser
instance-attribute
statement_parser = StatementParser(terminators=terminators, multiline_commands=multiline_commands, shortcuts=shortcuts)
doc_header
instance-attribute
always_prefix_settables
property
writable
Flags whether CommandSet settable values should always be prefixed
RETURNS | DESCRIPTION |
---|---|
bool
|
True if CommandSet settable values will always be prefixed. False if not. |
settables
property
Get all available user-settable attributes. This includes settables defined in installed CommandSets
RETURNS | DESCRIPTION |
---|---|
Mapping[str, Settable]
|
Mapping from attribute-name to Settable of all user-settable attributes from |
allow_style
property
writable
Read-only property needed to support do_set when it reads allow_style
visible_prompt
property
Read-only property to get the visible prompt with any ANSI style escape codes stripped.
Used by transcript testing to make it easier and more reliable when users are doing things like coloring the prompt using ANSI color codes.
RETURNS | DESCRIPTION |
---|---|
str
|
prompt stripped of any ANSI escape codes |
alias_description
class-attribute
instance-attribute
alias_description = 'Manage aliases\n\nAn alias is a command that enables replacement of a word by another string.'
alias_parser
class-attribute
instance-attribute
alias_parser = DEFAULT_ARGUMENT_PARSER(description=alias_description, epilog=alias_epilog)
alias_create_description
class-attribute
instance-attribute
alias_create_epilog
class-attribute
instance-attribute
alias_create_epilog = 'Notes:\n If you want to use redirection, pipes, or terminators in the value of the\n alias, then quote them.\n\n Since aliases are resolved during parsing, tab completion will function as\n it would for the actual command the alias resolves to.\n\nExamples:\n alias create ls !ls -lF\n alias create show_log !cat "log file.txt"\n alias create save_results print_results ">" out.txt\n'
alias_create_parser
class-attribute
instance-attribute
alias_create_parser = DEFAULT_ARGUMENT_PARSER(description=alias_create_description, epilog=alias_create_epilog)
alias_delete_description
class-attribute
instance-attribute
alias_delete_parser
class-attribute
instance-attribute
alias_delete_parser = DEFAULT_ARGUMENT_PARSER(description=alias_delete_description)
alias_list_description
class-attribute
instance-attribute
alias_list_description = 'List specified aliases in a reusable form that can be saved to a startup\nscript to preserve aliases across sessions\n\nWithout arguments, all aliases will be listed.'
alias_list_parser
class-attribute
instance-attribute
alias_list_parser = DEFAULT_ARGUMENT_PARSER(description=alias_list_description)
macro_description
class-attribute
instance-attribute
macro_description = 'Manage macros\n\nA macro is similar to an alias, but it can contain argument placeholders.'
macro_parser
class-attribute
instance-attribute
macro_parser = DEFAULT_ARGUMENT_PARSER(description=macro_description, epilog=macro_epilog)
macro_create_help
class-attribute
instance-attribute
macro_create_description
class-attribute
instance-attribute
macro_create_epilog
class-attribute
instance-attribute
macro_create_epilog = 'A macro is similar to an alias, but it can contain argument placeholders.\nArguments are expressed when creating a macro using {#} notation where {1}\nmeans the first argument.\n\nThe following creates a macro called my_macro that expects two arguments:\n\n macro create my_macro make_dinner --meat {1} --veggie {2}\n\nWhen the macro is called, the provided arguments are resolved and the\nassembled command is run. For example:\n\n my_macro beef broccoli ---> make_dinner --meat beef --veggie broccoli\n\nNotes:\n To use the literal string {1} in your command, escape it this way: {{1}}.\n\n Extra arguments passed to a macro are appended to resolved command.\n\n An argument number can be repeated in a macro. In the following example the\n first argument will populate both {1} instances.\n\n macro create ft file_taxes -p {1} -q {2} -r {1}\n\n To quote an argument in the resolved command, quote it during creation.\n\n macro create backup !cp "{1}" "{1}.orig"\n\n If you want to use redirection, pipes, or terminators in the value of the\n macro, then quote them.\n\n macro create show_results print_results -type {1} "|" less\n\n Because macros do not resolve until after hitting Enter, tab completion\n will only complete paths while typing a macro.'
macro_create_parser
class-attribute
instance-attribute
macro_create_parser = DEFAULT_ARGUMENT_PARSER(description=macro_create_description, epilog=macro_create_epilog)
macro_delete_description
class-attribute
instance-attribute
macro_delete_parser
class-attribute
instance-attribute
macro_delete_parser = DEFAULT_ARGUMENT_PARSER(description=macro_delete_description)
macro_list_description
class-attribute
instance-attribute
macro_list_description = 'List specified macros in a reusable form that can be saved to a startup script\nto preserve macros across sessions\n\nWithout arguments, all macros will be listed.'
macro_list_parser
class-attribute
instance-attribute
macro_list_parser = DEFAULT_ARGUMENT_PARSER(description=macro_list_description)
help_parser
class-attribute
instance-attribute
help_parser = DEFAULT_ARGUMENT_PARSER(description='List available commands or provide detailed help for a specific command')
shortcuts_parser
class-attribute
instance-attribute
shortcuts_parser = DEFAULT_ARGUMENT_PARSER(description='List available shortcuts')
eof_parser
class-attribute
instance-attribute
eof_parser = DEFAULT_ARGUMENT_PARSER(description='Called when Ctrl-D is pressed', epilog=INTERNAL_COMMAND_EPILOG)
quit_parser
class-attribute
instance-attribute
quit_parser = DEFAULT_ARGUMENT_PARSER(description='Exit this application')
set_description
class-attribute
instance-attribute
set_description = "Set a settable parameter or show current settings of parameters\nCall without arguments for a list of all settable parameters with their values.\nCall with just param to view that parameter's value."
set_parser_parent
class-attribute
instance-attribute
set_parser_parent = DEFAULT_ARGUMENT_PARSER(description=set_description, add_help=False)
set_parser
class-attribute
instance-attribute
set_parser = DEFAULT_ARGUMENT_PARSER(parents=[set_parser_parent])
shell_parser
class-attribute
instance-attribute
shell_parser = DEFAULT_ARGUMENT_PARSER(description='Execute a command as if at the OS prompt')
py_parser
class-attribute
instance-attribute
py_parser = DEFAULT_ARGUMENT_PARSER(description='Run an interactive Python shell')
run_pyscript_parser
class-attribute
instance-attribute
run_pyscript_parser = DEFAULT_ARGUMENT_PARSER(description='Run a Python script file inside the console')
ipython_parser
class-attribute
instance-attribute
ipython_parser = DEFAULT_ARGUMENT_PARSER(description='Run an interactive IPython shell')
history_description
class-attribute
instance-attribute
history_parser
class-attribute
instance-attribute
history_parser = DEFAULT_ARGUMENT_PARSER(description=history_description)
history_action_group
class-attribute
instance-attribute
history_format_group
class-attribute
instance-attribute
history_arg_help
class-attribute
instance-attribute
history_arg_help = 'empty all history items\na one history item by number\na..b, a:b, a:, ..b items by indices (inclusive)\nstring items containing string\n/regex/ items matching regular expression'
edit_description
class-attribute
instance-attribute
edit_description = 'Run a text editor and optionally open a file with it\n\nThe editor used is determined by a settable parameter. To set it:\n\n set editor (program-name)'
edit_parser
class-attribute
instance-attribute
edit_parser = DEFAULT_ARGUMENT_PARSER(description=edit_description)
run_script_description
class-attribute
instance-attribute
run_script_description = 'Run commands in script file that is encoded as either ASCII or UTF-8 text\n\nScript should contain one command per line, just like the command would be\ntyped in the console.\n\nIf the -t/--transcript flag is used, this command instead records\nthe output of the script commands to a transcript for testing purposes.\n'
run_script_parser
class-attribute
instance-attribute
run_script_parser = DEFAULT_ARGUMENT_PARSER(description=run_script_description)
relative_run_script_description
class-attribute
instance-attribute
relative_run_script_description = run_script_description
relative_run_script_epilog
class-attribute
instance-attribute
relative_run_script_epilog = 'Notes:\n This command is intended to only be used within text file scripts.'
relative_run_script_parser
class-attribute
instance-attribute
relative_run_script_parser = DEFAULT_ARGUMENT_PARSER(description=relative_run_script_description, epilog=relative_run_script_epilog)
emptyline
Called when an empty line is entered in response to the prompt.
If this method is not overridden, it repeats the last nonempty command entered.
completedefault
Method called to complete an input line when no command-specific complete_*() method is available.
By default, it returns an empty list.
completenames
complete_help
find_commandsets
Find all CommandSets that match the provided CommandSet type. By default, locates a CommandSet that is an exact type match but may optionally return all CommandSets that are sub-classes of the provided type
PARAMETER | DESCRIPTION |
---|---|
commandset_type
|
CommandSet sub-class type to search for
TYPE:
|
subclass_match
|
If True, return all sub-classes of provided type, otherwise only search for exact match
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
List[CommandSet]
|
Matching CommandSets |
Source code in cmd2/cmd2.py
find_commandset_for_command
Finds the CommandSet that registered the command name
PARAMETER | DESCRIPTION |
---|---|
command_name
|
command name to search
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Optional[CommandSet]
|
CommandSet that provided the command |
Source code in cmd2/cmd2.py
register_command_set
Installs a CommandSet, loading all commands defined in the CommandSet
PARAMETER | DESCRIPTION |
---|---|
cmdset
|
CommandSet to load
TYPE:
|
Source code in cmd2/cmd2.py
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 |
|
unregister_command_set
Uninstalls a CommandSet and unloads all associated commands
PARAMETER | DESCRIPTION |
---|---|
cmdset
|
CommandSet to uninstall
TYPE:
|
Source code in cmd2/cmd2.py
add_settable
Add a settable parameter to self.settables
PARAMETER | DESCRIPTION |
---|---|
settable
|
Settable object being added
TYPE:
|
Source code in cmd2/cmd2.py
remove_settable
Convenience method for removing a settable parameter from self.settables
PARAMETER | DESCRIPTION |
---|---|
name
|
name of the settable being removed
TYPE:
|
RAISES | DESCRIPTION |
---|---|
KeyError
|
if the Settable matches this name |
Source code in cmd2/cmd2.py
build_settables
Create the dictionary of user-settable parameters
Source code in cmd2/cmd2.py
print_to
Print message to a given file object.
PARAMETER | DESCRIPTION |
---|---|
dest
|
the file object being written to
TYPE:
|
msg
|
object to print
TYPE:
|
end
|
string appended after the end of the message, default a newline
TYPE:
|
style
|
optional style function to format msg with (e.g. ansi.style_success)
TYPE:
|
Source code in cmd2/cmd2.py
poutput
Print message to self.stdout and appends a newline by default
PARAMETER | DESCRIPTION |
---|---|
msg
|
object to print
TYPE:
|
end
|
string appended after the end of the message, default a newline
TYPE:
|
Source code in cmd2/cmd2.py
perror
Print message to sys.stderr
PARAMETER | DESCRIPTION |
---|---|
msg
|
object to print
TYPE:
|
end
|
string appended after the end of the message, default a newline
TYPE:
|
apply_style
|
If True, then ansi.style_error will be applied to the message text. Set to False in cases where the message text already has the desired style. Defaults to True.
TYPE:
|
Source code in cmd2/cmd2.py
psuccess
Wraps poutput, but applies ansi.style_success by default
PARAMETER | DESCRIPTION |
---|---|
msg
|
object to print
TYPE:
|
end
|
string appended after the end of the message, default a newline
TYPE:
|
Source code in cmd2/cmd2.py
pwarning
Wraps perror, but applies ansi.style_warning by default
PARAMETER | DESCRIPTION |
---|---|
msg
|
object to print
TYPE:
|
end
|
string appended after the end of the message, default a newline
TYPE:
|
Source code in cmd2/cmd2.py
pexcept
Print Exception message to sys.stderr. If debug is true, print exception traceback if one exists.
PARAMETER | DESCRIPTION |
---|---|
msg
|
message or Exception to print
TYPE:
|
end
|
string appended after the end of the message, default a newline
TYPE:
|
apply_style
|
If True, then ansi.style_error will be applied to the message text. Set to False in cases where the message text already has the desired style. Defaults to True.
TYPE:
|
Source code in cmd2/cmd2.py
pfeedback
For printing nonessential feedback. Can be silenced with quiet
.
Inclusion in redirected output is controlled by feedback_to_output
.
PARAMETER | DESCRIPTION |
---|---|
msg
|
object to print
TYPE:
|
end
|
string appended after the end of the message, default a newline
TYPE:
|
Source code in cmd2/cmd2.py
ppaged
Print output using a pager if it would go off screen and stdout isn't currently being redirected.
Never uses a pager inside a script (Python or text) or when output is being redirected or piped or when stdout or stdin are not a fully functional terminal.
PARAMETER | DESCRIPTION |
---|---|
msg
|
object to print
TYPE:
|
end
|
string appended after the end of the message, default a newline
TYPE:
|
chop
|
True -> causes lines longer than the screen width to be chopped (truncated) rather than wrapped - truncated text is still accessible by scrolling with the right & left arrow keys - chopping is ideal for displaying wide tabular data as is done in utilities like pgcli False -> causes lines longer than the screen width to wrap to the next line - wrapping is ideal when you want to keep users from having to use horizontal scrolling WARNING: On Windows, the text always wraps regardless of what the chop argument is set to
TYPE:
|
Source code in cmd2/cmd2.py
tokens_for_completion
Used by tab completion functions to get all tokens through the one being completed.
PARAMETER | DESCRIPTION |
---|---|
line
|
the current input line with leading whitespace removed
TYPE:
|
begidx
|
the beginning index of the prefix text
TYPE:
|
endidx
|
the ending index of the prefix text
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Tuple[List[str], List[str]]
|
A 2 item tuple where the items are On Success - tokens: list of unquoted tokens - this is generally the list needed for tab completion functions - raw_tokens: list of tokens with any quotes preserved = this can be used to know if a token was quoted or is missing a closing quote Both lists are guaranteed to have at least 1 item. The last item in both lists is the token being tab completed On Failure - Two empty lists |
Source code in cmd2/cmd2.py
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 |
|
basic_complete
Basic tab completion function that matches against a list of strings without considering line contents or cursor position. The args required by this function are defined in the header of Python's cmd.py.
PARAMETER | DESCRIPTION |
---|---|
text
|
the string prefix we are attempting to match (all matches must begin with it)
TYPE:
|
line
|
the current input line with leading whitespace removed
TYPE:
|
begidx
|
the beginning index of the prefix text
TYPE:
|
endidx
|
the ending index of the prefix text
TYPE:
|
match_against
|
the strings being matched against
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
List[str]
|
a list of possible tab completions |
Source code in cmd2/cmd2.py
delimiter_complete
Performs tab completion against a list but each match is split on a delimiter and only the portion of the match being tab completed is shown as the completion suggestions. This is useful if you match against strings that are hierarchical in nature and have a common delimiter.
An easy way to illustrate this concept is path completion since paths are just directories/files delimited by a slash. If you are tab completing items in /home/user you don't get the following as suggestions:
/home/user/file.txt /home/user/program.c /home/user/maps/ /home/user/cmd2.py
Instead you are shown:
file.txt program.c maps/ cmd2.py
For a large set of data, this can be visually more pleasing and easier to search.
Another example would be strings formatted with the following syntax: company::department::name In this case the delimiter would be :: and the user could easily narrow down what they are looking for if they were only shown suggestions in the category they are at in the string.
PARAMETER | DESCRIPTION |
---|---|
text
|
the string prefix we are attempting to match (all matches must begin with it)
TYPE:
|
line
|
the current input line with leading whitespace removed
TYPE:
|
begidx
|
the beginning index of the prefix text
TYPE:
|
endidx
|
the ending index of the prefix text
TYPE:
|
match_against
|
the list being matched against
TYPE:
|
delimiter
|
what delimits each portion of the matches (ex: paths are delimited by a slash)
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
List[str]
|
a list of possible tab completions |
Source code in cmd2/cmd2.py
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 |
|
flag_based_complete
Tab completes based on a particular flag preceding the token being completed.
PARAMETER | DESCRIPTION |
---|---|
text
|
the string prefix we are attempting to match (all matches must begin with it)
TYPE:
|
line
|
the current input line with leading whitespace removed
TYPE:
|
begidx
|
the beginning index of the prefix text
TYPE:
|
endidx
|
the ending index of the prefix text
TYPE:
|
flag_dict
|
dictionary whose structure is the following:
TYPE:
|
all_else
|
an optional parameter for tab completing any token that isn't preceded by a flag in flag_dict
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
List[str]
|
a list of possible tab completions |
Source code in cmd2/cmd2.py
index_based_complete
Tab completes based on a fixed position in the input string.
PARAMETER | DESCRIPTION |
---|---|
text
|
the string prefix we are attempting to match (all matches must begin with it)
TYPE:
|
line
|
the current input line with leading whitespace removed
TYPE:
|
begidx
|
the beginning index of the prefix text
TYPE:
|
endidx
|
the ending index of the prefix text
TYPE:
|
index_dict
|
dictionary whose structure is the following:
TYPE:
|
all_else
|
an optional parameter for tab completing any token that isn't at an index in index_dict
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
List[str]
|
a list of possible tab completions |
Source code in cmd2/cmd2.py
path_complete
Performs completion of local file system paths
PARAMETER | DESCRIPTION |
---|---|
text
|
the string prefix we are attempting to match (all matches must begin with it)
TYPE:
|
line
|
the current input line with leading whitespace removed
TYPE:
|
begidx
|
the beginning index of the prefix text
TYPE:
|
endidx
|
the ending index of the prefix text
TYPE:
|
path_filter
|
optional filter function that determines if a path belongs in the results this function takes a path as its argument and returns True if the path should be kept in the results
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
List[str]
|
a list of possible tab completions |
Source code in cmd2/cmd2.py
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 |
|
shell_cmd_complete
Performs completion of executables either in a user's path or a given path
PARAMETER | DESCRIPTION |
---|---|
text
|
the string prefix we are attempting to match (all matches must begin with it)
TYPE:
|
line
|
the current input line with leading whitespace removed
TYPE:
|
begidx
|
the beginning index of the prefix text
TYPE:
|
endidx
|
the ending index of the prefix text
TYPE:
|
complete_blank
|
If True, then a blank will complete all shell commands in a user's path. If False, then no completion is performed. Defaults to False to match Bash shell behavior.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
List[str]
|
a list of possible tab completions |
Source code in cmd2/cmd2.py
complete
Override of cmd's complete method which returns the next possible completion for 'text'
This completer function is called by readline as complete(text, state), for state in 0, 1, 2, …, until it returns a non-string value. It should return the next possible completion starting with text.
Since readline suppresses any exception raised in completer functions, they can be difficult to debug. Therefore, this function wraps the actual tab completion logic and prints to stderr any exception that occurs before returning control to readline.
PARAMETER | DESCRIPTION |
---|---|
text
|
the current word that user is typing
TYPE:
|
state
|
non-negative integer
TYPE:
|
custom_settings
|
used when not tab completing the main command line
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Optional[str]
|
the next possible completion for text or None |
Source code in cmd2/cmd2.py
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 |
|
in_script
in_pyscript
get_names
get_all_commands
Return a list of all commands
Source code in cmd2/cmd2.py
get_visible_commands
Return a list of commands that have not been hidden or disabled
Source code in cmd2/cmd2.py
get_help_topics
Return a list of help topics
Source code in cmd2/cmd2.py
sigint_handler
Signal handler for SIGINTs which typically come from Ctrl-C events.
If you need custom SIGINT behavior, then override this method.
PARAMETER | DESCRIPTION |
---|---|
signum
|
signal number
TYPE:
|
_
|
the current stack frame or None
TYPE:
|
Source code in cmd2/cmd2.py
termination_signal_handler
Signal handler for SIGHUP and SIGTERM. Only runs on Linux and Mac.
SIGHUP - received when terminal window is closed SIGTERM - received when this app has been requested to terminate
The basic purpose of this method is to call sys.exit() so our exit handler will run and save the persistent history file. If you need more complex behavior like killing threads and performing cleanup, then override this method.
PARAMETER | DESCRIPTION |
---|---|
signum
|
signal number
TYPE:
|
_
|
the current stack frame or None
TYPE:
|
Source code in cmd2/cmd2.py
precmd
Hook method executed just before the command is executed by cmd2.Cmd.onecmd and after adding it to history.
PARAMETER | DESCRIPTION |
---|---|
statement
|
subclass of str which also contains the parsed input
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Statement
|
a potentially modified version of the input Statement object See cmd2.Cmd.register_postparsing_hook and cmd2.Cmd.register_precmd_hook for more robust ways to run hooks before the command is executed. See Hooks for more information. |
Source code in cmd2/cmd2.py
postcmd
Hook method executed just after a command is executed by cmd2.Cmd.onecmd.
PARAMETER | DESCRIPTION |
---|---|
stop
|
return
TYPE:
|
statement
|
subclass of str which also contains the parsed input See cmd2.Cmd.register_postcmd_hook and cmd2.Cmd.register_cmdfinalization_hook for more robust ways to run hooks after the command is executed. See Hooks for more information.
TYPE:
|
Source code in cmd2/cmd2.py
preloop
Hook method executed once when the cmd2.Cmd.cmdloop method is called.
See cmd2.Cmd.register_preloop_hook for a more robust way to run hooks before the command loop begins. See Hooks for more information.
Source code in cmd2/cmd2.py
postloop
Hook method executed once when the cmd2.Cmd.cmdloop method is about to return.
See cmd2.Cmd.register_postloop_hook for a more robust way to run hooks after the command loop completes. See Hooks for more information.
Source code in cmd2/cmd2.py
parseline
Parse the line into a command name and a string containing the arguments.
NOTE: This is an override of a parent class method. It is only used by other parent class methods.
Different from the parent class method, this ignores self.identchars.
PARAMETER | DESCRIPTION |
---|---|
line
|
line read by readline
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Tuple[str, str, str]
|
tuple containing (command, args, line) |
Source code in cmd2/cmd2.py
onecmd_plus_hooks
onecmd_plus_hooks(line, *, add_to_history=True, raise_keyboard_interrupt=False, py_bridge_call=False, orig_rl_history_length=None)
Top-level function called by cmdloop() to handle parsing a line and running the command and all of its hooks.
PARAMETER | DESCRIPTION |
---|---|
line
|
command line to run
TYPE:
|
add_to_history
|
If True, then add this command to history. Defaults to True.
TYPE:
|
raise_keyboard_interrupt
|
if True, then KeyboardInterrupt exceptions will be raised if stop isn't already True. This is used when running commands in a loop to be able to stop the whole loop and not just the current command. Defaults to False.
TYPE:
|
py_bridge_call
|
This should only ever be set to True by PyBridge to signify the beginning of an app() call from Python. It is used to enable/disable the storage of the command's stdout.
TYPE:
|
orig_rl_history_length
|
Optional length of the readline history before the current command was typed. This is used to assist in combining multiline readline history entries and is only populated by cmd2. Defaults to None.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
bool
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 |
|
runcmds_plus_hooks
Used when commands are being run in an automated fashion like text scripts or history replays. The prompt and command line for each command will be printed if echo is True.
PARAMETER | DESCRIPTION |
---|---|
cmds
|
commands to run
TYPE:
|
add_to_history
|
If True, then add these commands to history. Defaults to True.
TYPE:
|
stop_on_keyboard_interrupt
|
if True, then stop running contents of cmds if Ctrl-C is pressed instead of moving to the next command in the list. This is used when the commands are part of a group, like a text script, which should stop upon Ctrl-C. Defaults to False.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
bool
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
cmd_func
Get the function for a command
PARAMETER | DESCRIPTION |
---|---|
command
|
the name of the command Example:
TYPE:
|
Source code in cmd2/cmd2.py
onecmd
This executes the actual do_* method for a command.
If the command provided doesn't exist, then it executes default() instead.
PARAMETER | DESCRIPTION |
---|---|
statement
|
intended to be a Statement instance parsed command from the input stream, alternative acceptance of a str is present only for backward compatibility with cmd
TYPE:
|
add_to_history
|
If True, then add this command to history. Defaults to True.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
bool
|
a flag indicating whether the interpretation of commands should stop |
Source code in cmd2/cmd2.py
default
Executed when the command given isn't a recognized command implemented by a do_* method.
PARAMETER | DESCRIPTION |
---|---|
statement
|
Statement object with parsed input
TYPE:
|
Source code in cmd2/cmd2.py
read_input
read_input(prompt, *, history=None, completion_mode=NONE, preserve_quotes=False, choices=None, choices_provider=None, completer=None, parser=None)
Read input from appropriate stdin value. Also supports tab completion and up-arrow history while input is being entered.
PARAMETER | DESCRIPTION |
---|---|
prompt
|
prompt to display to user
TYPE:
|
history
|
optional list of strings to use for up-arrow history. If completion_mode is CompletionMode.COMMANDS and this is None, then cmd2's command list history will be used. The passed in history will not be edited. It is the caller's responsibility to add the returned input to history if desired. Defaults to None.
TYPE:
|
completion_mode
|
tells what type of tab completion to support. Tab completion only works when self.use_rawinput is True and sys.stdin is a terminal. Defaults to CompletionMode.NONE. The following optional settings apply when completion_mode is CompletionMode.CUSTOM:
TYPE:
|
preserve_quotes
|
if True, then quoted tokens will keep their quotes when processed by ArgparseCompleter. This is helpful in cases when you're tab completing flag-like tokens (e.g. -o, --option) and you don't want them to be treated as argparse flags when quoted. Set this to True if you plan on passing the string to argparse with the tokens still quoted. A maximum of one of these should be provided:
TYPE:
|
choices
|
iterable of accepted values for single argument
TYPE:
|
choices_provider
|
function that provides choices for single argument
TYPE:
|
completer
|
tab completion function that provides choices for single argument
TYPE:
|
parser
|
an argument parser which supports the tab completion of multiple arguments
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
the line read from stdin with all trailing new lines removed |
RAISES | DESCRIPTION |
---|---|
Exception
|
any exceptions raised by input() and stdin.readline() |
Source code in cmd2/cmd2.py
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 |
|
do_alias
do_macro
complete_help_command
Completes the command argument of help
Source code in cmd2/cmd2.py
complete_help_subcommands
Completes the subcommands argument of help
Source code in cmd2/cmd2.py
do_help
List available commands or provide detailed help for a specific command
Source code in cmd2/cmd2.py
print_topics
Print groups of commands and topics in columns and an optional header Override of cmd's print_topics() to handle headers with newlines, ANSI style sequences, and wide characters
PARAMETER | DESCRIPTION |
---|---|
header
|
string to print above commands being printed
TYPE:
|
cmds
|
list of topics to print
TYPE:
|
cmdlen
|
unused, even by cmd's version
TYPE:
|
maxcol
|
max number of display columns to fit into
TYPE:
|
Source code in cmd2/cmd2.py
columnize
Display a list of single-line strings as a compact set of columns. Override of cmd's columnize() to handle strings with ANSI style sequences and wide characters
Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough).
Source code in cmd2/cmd2.py
do_shortcuts
List available shortcuts
Source code in cmd2/cmd2.py
do_eof
Called when Ctrl-D is pressed and calls quit with no arguments. This can be overridden if quit should be called differently.
Source code in cmd2/cmd2.py
do_quit
select
Presents a numbered menu to the user. Modeled after the bash shell's SELECT. Returns the item chosen.
Argument opts
can be:
| a single string -> will be split into one-word options | a list of strings -> will be offered as options | a list of tuples -> interpreted as (value, text), so that the return value can differ from the text advertised to the user
Source code in cmd2/cmd2.py
complete_set_value
Completes the value argument of set
Source code in cmd2/cmd2.py
do_set
Set a settable parameter or show current settings of parameters
Source code in cmd2/cmd2.py
do_shell
Execute a command as if at the OS prompt
Source code in cmd2/cmd2.py
do_py
Run an interactive Python shell
RETURNS | DESCRIPTION |
---|---|
Optional[bool]
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
do_run_pyscript
Run a Python script file inside the console
RETURNS | DESCRIPTION |
---|---|
Optional[bool]
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
do_ipy
Enter an interactive IPython shell
RETURNS | DESCRIPTION |
---|---|
Optional[bool]
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 |
|
do_history
View, run, edit, save, or clear previously entered commands
RETURNS | DESCRIPTION |
---|---|
Optional[bool]
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 |
|
do_edit
Run a text editor and optionally open a file with it
Source code in cmd2/cmd2.py
run_editor
Run a text editor and optionally open a file with it
PARAMETER | DESCRIPTION |
---|---|
file_path
|
optional path of the file to edit. Defaults to None.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
EnvironmentError
|
if self.editor is not set |
Source code in cmd2/cmd2.py
do_run_script
Run commands in script file that is encoded as either ASCII or UTF-8 text.
RETURNS | DESCRIPTION |
---|---|
Optional[bool]
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 |
|
do__relative_run_script
Run commands in script file that is encoded as either ASCII or UTF-8 text
RETURNS | DESCRIPTION |
---|---|
Optional[bool]
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
async_alert
Display an important message to the user while they are at a command line prompt. To the user it appears as if an alert message is printed above the prompt and their current input text and cursor location is left alone.
This function needs to acquire self.terminal_lock to ensure a prompt is on screen. Therefore, it is best to acquire the lock before calling this function to avoid raising a RuntimeError.
This function is only needed when you need to print an alert or update the prompt while the main thread is blocking at the prompt. Therefore, this should never be called from the main thread. Doing so will raise a RuntimeError.
PARAMETER | DESCRIPTION |
---|---|
alert_msg
|
the message to display to the user
TYPE:
|
new_prompt
|
If you also want to change the prompt that is displayed, then include it here. See async_update_prompt() docstring for guidance on updating a prompt.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
if called from the main thread. |
RuntimeError
|
if called while another thread holds |
Source code in cmd2/cmd2.py
5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 |
|
async_update_prompt
Update the command line prompt while the user is still typing at it.
This is good for alerting the user to system changes dynamically in between commands. For instance you could alter the color of the prompt to indicate a system status or increase a counter to report an event. If you do alter the actual text of the prompt, it is best to keep the prompt the same width as what's on screen. Otherwise the user's input text will be shifted and the update will not be seamless.
If user is at a continuation prompt while entering a multiline command, the onscreen prompt will not change. However, self.prompt will still be updated and display immediately after the multiline line command completes.
PARAMETER | DESCRIPTION |
---|---|
new_prompt
|
what to change the prompt to
TYPE:
|
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
if called from the main thread. |
RuntimeError
|
if called while another thread holds |
Source code in cmd2/cmd2.py
async_refresh_prompt
Refresh the oncreen prompt to match self.prompt.
One case where the onscreen prompt and self.prompt can get out of sync is when async_alert() is called while a user is in search mode (e.g. Ctrl-r). To prevent overwriting readline's onscreen search prompt, self.prompt is updated but readline's saved prompt isn't.
Therefore when a user aborts a search, the old prompt is still on screen until they press Enter or this method is called. Call need_prompt_refresh() in an async print thread to know when a refresh is needed.
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
if called from the main thread. |
RuntimeError
|
if called while another thread holds |
Source code in cmd2/cmd2.py
need_prompt_refresh
Check whether the onscreen prompt needs to be asynchronously refreshed to match self.prompt.
Source code in cmd2/cmd2.py
set_window_title
staticmethod
Set the terminal window title.
NOTE: This function writes to stderr. Therefore, if you call this during a command run by a pyscript, the string which updates the title will appear in that command's CommandResult.stderr data.
PARAMETER | DESCRIPTION |
---|---|
title
|
the new window title
TYPE:
|
Source code in cmd2/cmd2.py
enable_command
Enable a command by restoring its functions
PARAMETER | DESCRIPTION |
---|---|
command
|
the command being enabled
TYPE:
|
Source code in cmd2/cmd2.py
enable_category
Enable an entire category of commands
PARAMETER | DESCRIPTION |
---|---|
category
|
the category to enable
TYPE:
|
Source code in cmd2/cmd2.py
disable_command
Disable a command and overwrite its functions
PARAMETER | DESCRIPTION |
---|---|
command
|
the command being disabled
TYPE:
|
message_to_print
|
what to print when this command is run or help is called on it while disabled The variable cmd2.COMMAND_NAME can be used as a placeholder for the name of the command being disabled. ex: message_to_print = f"{cmd2.COMMAND_NAME} is currently disabled"
TYPE:
|
Source code in cmd2/cmd2.py
disable_category
Disable an entire category of commands.
PARAMETER | DESCRIPTION |
---|---|
category
|
the category to disable
TYPE:
|
message_to_print
|
what to print when anything in this category is run or help is called on it while disabled. The variable cmd2.COMMAND_NAME can be used as a placeholder for the name of the command being disabled. ex: message_to_print = f"{cmd2.COMMAND_NAME} is currently disabled"
TYPE:
|
Source code in cmd2/cmd2.py
cmdloop
This is an outer wrapper around _cmdloop() which deals with extra features provided by cmd2.
_cmdloop() provides the main loop equivalent to cmd.cmdloop(). This is a wrapper around that which deals with the following extra features provided by cmd2: - transcript testing - intro banner - exit code
PARAMETER | DESCRIPTION |
---|---|
intro
|
if provided this overrides self.intro and serves as the intro banner printed once at start
TYPE:
|
Source code in cmd2/cmd2.py
5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 |
|
register_preloop_hook
Register a function to be called at the beginning of the command loop.
register_postloop_hook
Register a function to be called at the end of the command loop.
register_postparsing_hook
Register a function to be called after parsing user input but before running the command
Source code in cmd2/cmd2.py
register_precmd_hook
Register a hook to be called before the command function.
Source code in cmd2/cmd2.py
register_postcmd_hook
Register a hook to be called after the command function.
Source code in cmd2/cmd2.py
register_cmdfinalization_hook
Register a hook to be called after a command is completed, whether it completes successfully or not.