cmd2.Cmd
cmd2.Cmd
Cmd(
completekey=None,
stdin=None,
stdout=None,
*,
allow_cli_args=True,
allow_clipboard=True,
allow_redirection=True,
auto_load_commands=False,
auto_suggest=True,
complete_in_thread=True,
command_sets=None,
enable_bottom_toolbar=False,
enable_rprompt=False,
include_ipy=False,
include_py=False,
intro="",
multiline_commands=None,
persistent_history_file="",
persistent_history_length=1000,
refresh_interval=0.0,
shortcuts=None,
silence_startup_script=False,
startup_script="",
suggest_similar_command=False,
terminators=None,
)
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
|
name of a completion key, default to 'tab'. (If None or an empty string, 'tab' is used)
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:
|
allow_cli_args
|
if
TYPE:
|
allow_clipboard
|
If False, cmd2 will disable clipboard interactions
TYPE:
|
allow_redirection
|
If
TYPE:
|
auto_load_commands
|
If True, cmd2 will check for all subclasses of
TYPE:
|
auto_suggest
|
If True, cmd2 will provide fish shell style auto-suggestions based on history. User can press right-arrow key to accept the provided suggestion.
TYPE:
|
complete_in_thread
|
if
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:
|
enable_bottom_toolbar
|
if
TYPE:
|
enable_rprompt
|
if
TYPE:
|
include_ipy
|
should the "ipy" command be included for an embedded IPython shell
TYPE:
|
include_py
|
should the "py" command be included for an embedded Python shell
TYPE:
|
intro
|
introduction to display at startup
TYPE:
|
multiline_commands
|
Iterable of commands allowed to accept multi-line input
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:
|
refresh_interval
|
How often, in seconds, to refresh the UI. Defaults to 0.0. prompt-toolkit already refreshes the UI every time a key is pressed. Set this value if you need the UI to update automatically without user input (e.g., for displaying a clock or background status updates in the bottom toolbar).
TYPE:
|
shortcuts
|
Mapping containing shortcuts for commands. If not supplied, then defaults to constants.DEFAULT_SHORTCUTS. If you do not want any shortcuts, pass None and an empty dictionary will be created.
TYPE:
|
silence_startup_script
|
if
TYPE:
|
startup_script
|
file path to a script to execute at startup
TYPE:
|
suggest_similar_command
|
if
TYPE:
|
terminators
|
Iterable 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 None.
TYPE:
|
Source code in cmd2/cmd2.py
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 689 690 691 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 | |
traceback_kwargs
instance-attribute
traceback_kwargs = {
"width": 100,
"code_width": None,
"show_locals": False,
"max_frames": 100,
"word_wrap": True,
"indent_guides": True,
}
main_session
instance-attribute
main_session = self._create_main_session(
auto_suggest=auto_suggest,
complete_in_thread=complete_in_thread,
completekey=completekey,
enable_bottom_toolbar=enable_bottom_toolbar,
enable_rprompt=enable_rprompt,
refresh_interval=refresh_interval,
)
statement_parser
instance-attribute
statement_parser = StatementParser(
terminators=terminators,
multiline_commands=multiline_commands,
shortcuts=shortcuts,
)
default_error
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
Property needed to support do_set when it reads allow_style.
traceback_show_locals
property
writable
Property needed to support do_set when it reads traceback_show_locals.
traceback_width
property
writable
Property needed to support do_set when it reads traceback_width.
visible_prompt
property
Read-only property to get the visible prompt with any ANSI style sequences stripped.
Useful for test frameworks doing comparisons without having to worry about color/style.
| 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[Any]]
|
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[Any] | 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
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 | |
unregister_command_set
Uninstalls a CommandSet and unloads all associated commands.
| PARAMETER | DESCRIPTION |
|---|---|
cmdset
|
CommandSet to uninstall
TYPE:
|
Source code in cmd2/cmd2.py
get_root_parser_and_subcmd_path
Tokenize a command string and resolve the associated root parser and relative subcommand path.
This helper handles the initial resolution of a command string (e.g., 'foo bar baz') by identifying 'foo' as the root command, retrieving its associated parser, and returning any remaining tokens (['bar', 'baz']) as a path relative to that parser for further traversal.
| PARAMETER | DESCRIPTION |
|---|---|
command
|
full space-delimited command path leading to a parser (e.g. 'foo' or 'foo bar')
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Cmd2ArgumentParser, list[str]]
|
a tuple containing the Cmd2ArgumentParser for the root command and a list of strings representing the relative path to the desired hosting parser. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if the command is empty, the root command is not found, or the root command does not use an argparse parser. |
Source code in cmd2/cmd2.py
attach_subcommand
Attach a parser as a subcommand to a command at the specified path.
| PARAMETER | DESCRIPTION |
|---|---|
record
|
SubcommandRecord object describing the subcommand
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
if record.parser is not an instance of Cmd2ArgumentParser (or subclass) |
ValueError
|
if the command path is invalid, doesn't support subcommands, or the subcommand already exists |
Source code in cmd2/cmd2.py
detach_subcommand
Detach a subcommand from a command at the specified path.
| PARAMETER | DESCRIPTION |
|---|---|
command
|
full command path (space-delimited) leading to the parser hosting the subcommand to be detached (e.g. 'foo bar')
TYPE:
|
subcommand
|
name of the subcommand to detach
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SubcommandRecord
|
a SubcommandRecord object describing the detached subcommand |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if the command path is invalid or the subcommand doesn't exist |
Source code in cmd2/cmd2.py
detach_all_subcommands
Detach all subcommands from a command at the specified path.
| PARAMETER | DESCRIPTION |
|---|---|
command
|
full command path (space-delimited) leading to the parser hosting the subcommands to be detached (e.g. 'foo bar')
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[SubcommandRecord]
|
a list of SubcommandRecord objects describing the detached subcommands |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if the command path is invalid or the command doesn't support subcommands |
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
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 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 | |
print_to
print_to(
file,
*objects,
sep=" ",
end="\n",
style=None,
soft_wrap=True,
justify=None,
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 the built-in print() function. 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:
|
justify
|
justify method ("left", "center", "right", "full"). Defaults to None.
TYPE:
|
emoji
|
If True, Rich will replace emoji codes (e.g.,
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 console.print().
TYPE:
|
kwargs
|
Arbitrary keyword arguments. This allows subclasses to extend the signature of this
method and still call See the Rich documentation for more details on emoji codes, markup tags, and highlighting.
TYPE:
|
Source code in cmd2/cmd2.py
1637 1638 1639 1640 1641 1642 1643 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 | |
poutput
poutput(
*objects,
sep=" ",
end="\n",
style=None,
soft_wrap=True,
justify=None,
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,
justify=None,
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,
justify=None,
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,
justify=None,
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
format_exception
Format an exception for printing.
If debug is true, a full traceback is included, if one exists.
| PARAMETER | DESCRIPTION |
|---|---|
exception
|
the exception to be printed.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
a formatted exception string |
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,
justify=None,
emoji=False,
markup=False,
highlight=False,
rich_print_kwargs=None,
**kwargs,
)
Print nonessential feedback where the output can be silenced with the quiet 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,
justify=None,
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. For details on the other parameters, refer to the
TYPE:
|
Source code in cmd2/cmd2.py
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 | |
ppretty
ppretty(
obj,
*,
file=None,
indent_size=4,
indent_guides=True,
max_length=None,
max_string=None,
max_depth=None,
expand_all=False,
end="\n",
)
Pretty print an object.
This is a cmd2-compatible replacement for rich.pretty.pprint().
| PARAMETER | DESCRIPTION |
|---|---|
obj
|
object to pretty print
TYPE:
|
file
|
file stream being written to or None for self.stdout. Defaults to None.
TYPE:
|
indent_size
|
number of spaces in indent. Defaults to 4.
TYPE:
|
indent_guides
|
enable indentation guides. Defaults to True.
TYPE:
|
max_length
|
maximum length of containers before abbreviating, or None for no abbreviation. Defaults to None.
TYPE:
|
max_string
|
maximum length of strings before truncating, or None to disable. Defaults to None.
TYPE:
|
max_depth
|
maximum depth for nested data structures, or None for unlimited depth. Defaults to None.
TYPE:
|
expand_all
|
Expand all containers. Defaults to False.
TYPE:
|
end
|
string to write at end of printed text. Defaults to a newline.
TYPE:
|
Source code in cmd2/cmd2.py
get_bottom_toolbar
Get the bottom toolbar content.
This method is called by prompt-toolkit while at the main prompt if enable_bottom_toolbar
was set to True during initialization. Because prompt-toolkit executes this callback
on every UI refresh (such as on every keypress or at scheduled refresh intervals), keeping
this function highly optimized is critical to ensuring the CLI remains responsive.
Override this if you want a bottom toolbar displaying contextual information useful for your application. This could be information like the application name, current state, or even a real-time clock.
| RETURNS | DESCRIPTION |
|---|---|
AnyFormattedText
|
Content to populate the bottom toolbar. |
Source code in cmd2/cmd2.py
get_rprompt
Provide text to populate the prompt-toolkit right prompt.
This method is called by prompt-toolkit while at the main prompt if enable_rprompt
was set to True during initialization. Because prompt-toolkit executes this callback
on every UI refresh (such as on every keypress or at scheduled refresh intervals), keeping
this function highly optimized is critical to ensuring the CLI remains responsive.
Override this if you want a right prompt displaying contextual information useful for your application. This could be information like the current Git branch, time, or current working directory that is displayed without cluttering the main input area.
| RETURNS | DESCRIPTION |
|---|---|
AnyFormattedText
|
Content to populate the right prompt. |
Source code in cmd2/cmd2.py
tokens_for_completion
Get all tokens through the one being completed, used by 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 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
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 | |
basic_complete
Perform completion without considering line contents or cursor position.
Strings are matched directly while CompletionItems are matched against their 'text' member.
| 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 items being matched against
TYPE:
|
sort
|
if True, then results will be sorted. If False, then items will be in the same order they appeared in match_against.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Completions
|
a Completions object |
Source code in cmd2/cmd2.py
delimiter_complete
Perform completion against a list but each match is split on a delimiter.
Only the portion of the match being 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 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 |
|---|---|
Completions
|
a Completions object |
Source code in cmd2/cmd2.py
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 | |
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 |
|---|---|
Completions
|
a Completions object |
Source code in cmd2/cmd2.py
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 | |
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 |
|---|---|
Completions
|
a Completions object |
Source code in cmd2/cmd2.py
complete
Handle completion for an input line.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
the current word that user is typing
TYPE:
|
line
|
current input line
TYPE:
|
begidx
|
beginning index of text
TYPE:
|
endidx
|
ending index of text
TYPE:
|
custom_settings
|
used when not completing the main command line
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Completions
|
a Completions object |
Source code in cmd2/cmd2.py
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 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 | |
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
pre_prompt
Ran just before the prompt is displayed (and after the event loop has started).
This is the ideal location to update self.prompt or any other state that should
be current when the prompt appears.
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
onecmd_plus_hooks
onecmd_plus_hooks(
line,
*,
add_to_history=True,
raise_keyboard_interrupt=False,
py_bridge_call=False,
)
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if running of commands should stop |
Source code in cmd2/cmd2.py
3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 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 | |
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
get_command_func
Get the bound command function for a command.
| PARAMETER | DESCRIPTION |
|---|---|
command
|
the name of the command
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BoundCommandFunc[...] | None
|
the bound function implementing the command, or None if not found |
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 a Completions object with no matches.
Source code in cmd2/cmd2.py
read_input
read_input(
prompt="",
*,
history=None,
preserve_quotes=False,
choices=None,
choices_provider=None,
completer=None,
parser=None,
)
Read a line of input with optional completion and history.
| PARAMETER | DESCRIPTION |
|---|---|
prompt
|
prompt to display to user
TYPE:
|
history
|
optional Sequence of strings to use for up-arrow history. 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:
|
preserve_quotes
|
if True, then quoted tokens will keep their quotes when processed by ArgparseCompleter. This is helpful in cases when you're 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
|
completion function that provides choices for single argument
TYPE:
|
parser
|
an argument parser which supports the completion of multiple arguments
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
the line read from stdin with all trailing new lines removed |
| RAISES | DESCRIPTION |
|---|---|
EOFError
|
if the input stream is closed or the user signals EOF (e.g., Ctrl+D) |
Exception
|
any other exceptions raised by prompt() |
Source code in cmd2/cmd2.py
read_secret
Read a secret from stdin without displaying the value on the screen.
| PARAMETER | DESCRIPTION |
|---|---|
prompt
|
prompt to display to user
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
the secret read from stdin with all trailing new lines removed |
| RAISES | DESCRIPTION |
|---|---|
EOFError
|
if the input stream is closed or the user signals EOF (e.g., Ctrl+D) |
Exception
|
any other exceptions raised by prompt() |
Source code in cmd2/cmd2.py
do_alias
macro_arg_complete
Completes arguments to a macro.
Its default behavior is to call path_complete, but you can override this as needed.
| 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 |
|---|---|
Completions
|
a Completions object |
Source code in cmd2/cmd2.py
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
4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 | |
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
|
Sequence 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
|
Sequence 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
|
Sequence 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 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
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 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 | |
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
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
5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 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 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 | |
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, or on Windows if the editor or file path contains a double quote |
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
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
add_alert
Queue an asynchronous alert to be displayed when the prompt is active.
Examples: add_alert(msg="System error!") # Print message only add_alert(prompt="user@host> ") # Update prompt only add_alert(msg="Done", prompt="> ") # Update both
| PARAMETER | DESCRIPTION |
|---|---|
msg
|
an optional printable object (including Rich renderables) to be printed above the prompt.
TYPE:
|
soft_wrap
|
Enable soft wrap mode. This only applies with msg is not None. Defaults to True. See print_to() docstring for more details on this parameter.
TYPE:
|
prompt
|
an optional string to dynamically replace the current prompt.
TYPE:
|
Source code in cmd2/cmd2.py
set_window_title
Set the title of this application's terminal.
The title is written to the output used by the main prompt, custom input prompts, and select() menus. That is a dummy output when stdin or stdout isn't a terminal, or when the terminal couldn't be set up. In that case, the title is written to the stdout this app was created with instead, if that is a terminal. Otherwise, no title is written.
This can be called from any thread. If no prompt is running, then the title is written and flushed before this returns, and output errors propagate to the caller. Such a direct write from another thread isn't synchronized with other writers to the terminal, such as a prompt which is just starting or finishing.
While a prompt is running, the title is written on the prompt's event loop, even when this is called on that loop, so it doesn't interleave with rendering. It appears once the loop runs its next callback, which can be delayed while the loop is busy, such as in a slow completer. If several titles are set before then, only the latest is written. Output errors are ignored so they can't disrupt the prompt.
| 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 replace its functions with disabled versions.
| 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: - intro banner - exit code
| PARAMETER | DESCRIPTION |
|---|---|
intro
|
if provided this overrides self.intro and serves as the intro banner printed once at start
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
exit code |
Source code in cmd2/cmd2.py
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.