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=False, allow_clipboard=True, suggest_similar_command=False, intro='')
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.
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
314 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 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 | |
statement_parser
instance-attribute
statement_parser = StatementParser(terminators=terminators, multiline_commands=multiline_commands, shortcuts=shortcuts)
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 sequences stripped.
Used by transcript testing to make it easier and more reliable when users are doing things like coloring the prompt.
| RETURNS | DESCRIPTION |
|---|---|
str
|
the stripped prompt |
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
Find the CommandSet that registered the command name.
| PARAMETER | DESCRIPTION |
|---|---|
command_name
|
command name to search
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CommandSet | None
|
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
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 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | |
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
Remove 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_to(file, *objects, sep=' ', end='\n', style=None, soft_wrap=True, emoji=False, markup=False, highlight=False, rich_print_kwargs=None, **kwargs)
Print objects to a given file stream.
This method is configured for general-purpose printing. By default, it enables soft wrap and disables Rich's automatic detection for markup, emoji, and highlighting. These defaults can be overridden by passing explicit keyword arguments.
| PARAMETER | DESCRIPTION |
|---|---|
file
|
file stream being written to
TYPE:
|
objects
|
objects to print
TYPE:
|
sep
|
string to write between printed text. Defaults to " ".
TYPE:
|
end
|
string to write at end of printed text. Defaults to a newline.
TYPE:
|
style
|
optional style to apply to output
TYPE:
|
soft_wrap
|
Enable soft wrap mode. Defaults to True. If True, text that doesn't fit will run on to the following line, just like with print(). This is useful for raw text and logs. If False, Rich wraps text to fit the terminal width. Set this to False when printing structured Renderables like Tables, Panels, or Columns to ensure they render as expected. For example, when soft_wrap is True Panels truncate text which is wider than the terminal.
TYPE:
|
emoji
|
If True, Rich will replace emoji codes (e.g., ) with their corresponding Unicode characters. Defaults to False.
TYPE:
|
markup
|
If True, Rich will interpret strings with tags (e.g., [bold]hello[/bold]) as styled output. Defaults to False.
TYPE:
|
highlight
|
If True, Rich will automatically apply highlighting to elements within strings, such as common Python data types like numbers, booleans, or None. This is particularly useful when pretty printing objects like lists and dictionaries to display them in color. Defaults to False.
TYPE:
|
rich_print_kwargs
|
optional additional keyword arguments to pass to Rich's Console.print().
TYPE:
|
kwargs
|
Arbitrary keyword arguments. This allows subclasses to extend the signature of this method and still call
TYPE:
|
Source code in cmd2/cmd2.py
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 | |
poutput
poutput(*objects, sep=' ', end='\n', style=None, soft_wrap=True, emoji=False, markup=False, highlight=False, rich_print_kwargs=None, **kwargs)
Print objects to self.stdout.
For details on the parameters, refer to the print_to method documentation.
Source code in cmd2/cmd2.py
perror
perror(*objects, sep=' ', end='\n', style=ERROR, soft_wrap=True, emoji=False, markup=False, highlight=False, rich_print_kwargs=None, **kwargs)
Print objects to sys.stderr.
| PARAMETER | DESCRIPTION |
|---|---|
style
|
optional style to apply to output. Defaults to Cmd2Style.ERROR. For details on the other parameters, refer to the
TYPE:
|
Source code in cmd2/cmd2.py
psuccess
psuccess(*objects, sep=' ', end='\n', soft_wrap=True, emoji=False, markup=False, highlight=False, rich_print_kwargs=None, **kwargs)
Wrap poutput, but apply Cmd2Style.SUCCESS.
For details on the parameters, refer to the print_to method documentation.
Source code in cmd2/cmd2.py
pwarning
pwarning(*objects, sep=' ', end='\n', soft_wrap=True, emoji=False, markup=False, highlight=False, rich_print_kwargs=None, **kwargs)
Wrap perror, but apply Cmd2Style.WARNING.
For details on the parameters, refer to the print_to method documentation.
Source code in cmd2/cmd2.py
pexcept
Print an exception to sys.stderr.
If debug is true, a full traceback is also printed, if one exists.
| PARAMETER | DESCRIPTION |
|---|---|
exception
|
the exception to be printed.
TYPE:
|
kwargs
|
Arbitrary keyword arguments. This allows subclasses to extend the signature of this method and still call
TYPE:
|
Source code in cmd2/cmd2.py
pfeedback
pfeedback(*objects, sep=' ', end='\n', style=None, soft_wrap=True, emoji=False, markup=False, highlight=False, rich_print_kwargs=None, **kwargs)
Print nonessential feedback.
The output can be silenced with the quiet setting and its inclusion in redirected output
is controlled by the feedback_to_output setting.
For details on the parameters, refer to the print_to method documentation.
Source code in cmd2/cmd2.py
ppaged
ppaged(*objects, sep=' ', end='\n', style=None, chop=False, soft_wrap=True, emoji=False, markup=False, highlight=False, rich_print_kwargs=None, **kwargs)
Print output using a pager.
A pager is used when the terminal is interactive and may exit immediately if the output
fits on the screen. A pager is not used inside a script (Python or text) or when output is
redirected or piped, and in these cases, output is sent to poutput.
| PARAMETER | DESCRIPTION |
|---|---|
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:
|
soft_wrap
|
Enable soft wrap mode. If True, lines of text will not be word-wrapped or cropped to fit the terminal width. Defaults to True. Note: If chop is True and a pager is used, soft_wrap is automatically set to True to prevent wrapping and allow for horizontal scrolling. For details on the other parameters, refer to the
TYPE:
|
Source code in cmd2/cmd2.py
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 | |
tokens_for_completion
Get all tokens through the one being completed, used by tab completion functions.
| 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
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 | |
basic_complete
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
Perform tab completion against a list but each match is split on a delimiter.
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
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 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 | |
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
Perform 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
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 | |
shell_cmd_complete
Perform 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 |
|---|---|
str | None
|
the next possible completion for text or None |
Source code in cmd2/cmd2.py
2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 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 | |
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:
|
frame
|
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
Ran just before the command is executed by cmd2.Cmd.onecmd and after adding it to history (cmd Hook method).
| 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
Ran just after a command is executed by cmd2.Cmd.onecmd (cmd inherited Hook method).
| 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
Ran once when the cmd2.Cmd.cmdloop method is called (cmd inherited Hook method).
This method is a stub that does nothing and exists to be overridden by subclasses.
See cmd2.Cmd.register_preloop_hook for a more robust wayto run hooks before the command loop begins. See Hooks for more information.
Source code in cmd2/cmd2.py
postloop
Ran once when the cmd2.Cmd.cmdloop method is about to return (cmd inherited Hook Method).
This method is a stub that does nothing and exists to be overridden by subclasses.
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.
| 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
2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 | |
runcmds_plus_hooks
Run commands in an automated fashion from sources 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
Execute 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
Execute 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
completedefault
Call to complete an input line when no command-specific complete_*() method is available.
This method is only called for non-argparse-based commands.
By default, it returns an empty list.
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
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 | |
do_alias
Manage aliases.
macro_arg_complete
Tab completes arguments to a macro.
Its default behavior is to call path_complete, but you can override this as needed.
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:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
a list of possible tab completions |
Source code in cmd2/cmd2.py
do_macro
Manage macros.
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
4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 | |
print_topics
Print groups of commands and topics in columns and an optional header.
Override of cmd's print_topics() to use Rich.
| 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
render_columns
Render a list of single-line strings as a compact set of columns.
This method correctly handles strings containing ANSI style sequences and full-width characters (like those used in CJK languages). Each column is only as wide as necessary and columns are separated by two spaces.
| PARAMETER | DESCRIPTION |
|---|---|
str_list
|
list of single-line strings to display
TYPE:
|
display_width
|
max number of display columns to fit into
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
a string containing the columnized output |
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() that uses the render_columns() method. The method correctly handles strings with ANSI style sequences and full-width characters (like those used in CJK languages).
| PARAMETER | DESCRIPTION |
|---|---|
str_list
|
list of single-line strings to display
TYPE:
|
display_width
|
max number of display columns to fit into
TYPE:
|
Source code in cmd2/cmd2.py
do_shortcuts
List available shortcuts.
Source code in cmd2/cmd2.py
do_eof
Quit with no arguments, called when Ctrl-D is pressed.
This can be overridden if quit should be called differently.
Source code in cmd2/cmd2.py
do_quit
select
Present 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 |
|---|---|
bool | None
|
True if running of commands should stop. |
Source code in cmd2/cmd2.py
do_run_pyscript
Run Python script within this application's environment.
| RETURNS | DESCRIPTION |
|---|---|
bool | None
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
do_ipy
Run an interactive IPython shell.
| RETURNS | DESCRIPTION |
|---|---|
bool | None
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 | |
do_history
View, run, edit, save, or clear previously entered commands.
| RETURNS | DESCRIPTION |
|---|---|
bool | None
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
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 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 | |
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 |
|---|---|
ValueError
|
if self.editor is not set |
Source code in cmd2/cmd2.py
do_run_script
Run text script.
| RETURNS | DESCRIPTION |
|---|---|
bool | None
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
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 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 | |
do__relative_run_script
Run text script.
This command is intended to be used from within a text script.
| RETURNS | DESCRIPTION |
|---|---|
bool | None
|
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
5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 | |
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.
| 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
Deal with extra features provided by cmd2, this is an outer wrapper around _cmdloop().
_cmdloop() provides the main loop. This provides 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
5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 | |
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.