Initialization
Here is a basic example cmd2 application which demonstrates many capabilities which you may wish to utilize while initializing the app:
examples/getting_started.py
#!/usr/bin/env python3
"""An example cmd2 application demonstrating many common features.
Features demonstrated include all of the following:
1) Colorizing/stylizing output
2) Persistent history
3) How to run an initialization script at startup
4) How to group and categorize commands when displaying them in help
5) Opting-in to using the ipy command to run an IPython shell
6) Allowing access to your application in py and ipy
7) Displaying an intro banner upon starting your application
8) Using a custom prompt
9) How to make custom attributes settable at runtime
10) Shortcuts for commands
11) Persistent bottom toolbar with realtime status updates
12) Right prompt which displays contextual information
13) Background thread to update the content displayed by the bottom toolbar outside of the UI thread to keep things responsive
14) Using preloop() and postloop() hooks to start and stop a background thread
15) Using the with_annotated decorator to parse typed command arguments
16) Using the with_argparser decorator to parse command arguments with a custom parser
"""
import argparse
import datetime
import pathlib
import sys
import threading
from typing import Annotated
from prompt_toolkit.application import get_app
from prompt_toolkit.formatted_text import AnyFormattedText
from rich.style import Style
import cmd2
from cmd2 import (
Color,
stylize,
)
from cmd2.annotated import Option
class BasicApp(cmd2.Cmd):
"""Cmd2 application to demonstrate many common features."""
DEFAULT_CATEGORY = "My Custom Commands"
def __init__(self) -> None:
"""Initialize the cmd2 application."""
# Startup script that defines a couple aliases for running shell commands
alias_script = pathlib.Path(__file__).absolute().parent / ".cmd2rc"
# Create a shortcut for one of our commands
shortcuts = cmd2.DEFAULT_SHORTCUTS
shortcuts.update({"&": "intro"})
super().__init__(
auto_suggest=True,
enable_bottom_toolbar=True,
enable_rprompt=True,
include_ipy=True,
persistent_history_file="cmd2_history.dat",
refresh_interval=0.5, # refresh the UI twice a second to keep the bottom toolbar timestamp current
shortcuts=shortcuts,
startup_script=str(alias_script),
)
# Prints an intro banner once upon application startup
self.intro = (
stylize(
"Welcome to cmd2!",
style=Style(color=Color.GREEN1, bgcolor=Color.GRAY0, bold=True),
)
+ " Note the full Unicode support: 😇 💩"
+ " and the persistent bottom bar with realtime status updates!"
)
# Show this as the prompt when asking for input
self.prompt = "myapp> "
# Allow access to your application in py and ipy via self
self.self_in_py = True
# Color to output text in with echo command
self.foreground_color = Color.CYAN.value
# Make echo_fg settable at runtime
fg_colors = [c.value for c in Color]
self.add_settable(
cmd2.Settable(
"foreground_color",
str,
"Foreground color to use with echo command",
self,
choices=fg_colors,
)
)
# Initialize background thread state for the bottom toolbar
self._toolbar_state = {"now": ""}
self._toolbar_lock = threading.Lock()
self._stop_thread_event = threading.Event()
self._toolbar_thread: threading.Thread | None = None
def _update_toolbar_state(self) -> None:
"""Background thread worker to update toolbar state continuously."""
while not self._stop_thread_event.is_set():
# Get the current time in ISO format with 0.01s precision
dt = datetime.datetime.now(datetime.timezone.utc).astimezone()
now = dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-4] + dt.strftime("%z")
with self._toolbar_lock:
self._toolbar_state["now"] = now
# Sleep to yield CPU, polling 4 times a second
self._stop_thread_event.wait(0.25)
def preloop(self) -> None:
"""Hook method executed once when the cmdloop() method is called."""
self._stop_thread_event.clear()
self._toolbar_thread = threading.Thread(target=self._update_toolbar_state, daemon=True)
self._toolbar_thread.start()
def postloop(self) -> None:
"""Hook method executed once when the cmdloop() method is about to return."""
if self._toolbar_thread and self._toolbar_thread.is_alive():
self._stop_thread_event.set()
self._toolbar_thread.join()
def get_bottom_toolbar(self) -> AnyFormattedText:
left_text = sys.argv[0]
with self._toolbar_lock:
now = self._toolbar_state.get("now", "")
# Fetch the terminal width to calculate padding for right-alignment.
# If called outside a running app loop (e.g., in unit tests), get_app()
# safely returns a dummy app with an 80-column fallback.
cols = get_app().output.get_size().columns
padding_size = cols - len(left_text) - len(now)
if padding_size < 1:
padding_size = 1
padding = " " * padding_size
# Return formatted text for prompt-toolkit
return [
("ansigreen", left_text),
("", padding),
("ansicyan", now),
]
def get_rprompt(self) -> AnyFormattedText:
current_working_directory = pathlib.Path.cwd()
style = "bg:ansired fg:ansiwhite"
text = f"cwd={current_working_directory}"
return [(style, text)]
@cmd2.with_annotated
def do_cat(
self,
path: pathlib.Path, # Required positional argument with type annotation, tab-completes filesystem paths automatically
numbered: Annotated[ # Optional flag argument with type annotation, default value, and help text
bool, Option("-n", "--number", help_text="prefix each line with its number")
] = False,
) -> None:
"""Print a file's contents. `path` tab-completes filesystem paths automatically.
Try:
cat <TAB> # path completes files/dirs -- no completer wired
cat notes.txt
cat notes.txt -n # -n / --number, declared via Option metadata
cat notes.txt --no-number
"""
text = path.read_text()
lines = text.splitlines()
if numbered:
numbered_lines = []
for index, line in enumerate(lines, start=1):
numbered_lines.append(f"{index}: {line}")
self.ppaged("\n".join(numbered_lines))
else:
# Just print the contents using a pager
self.ppaged(path.read_text())
def do_intro(self, _: cmd2.Statement) -> None:
"""Display the intro banner.
This command uses raw statement parsing. In general, we strongly recommend against this approach. But since this
command effectively takes no arguments, it is safe to use raw statement parsing here.
The & key is also used as a shortcut for this command, so you can also type & to display the intro banner.
"""
self.poutput(self.intro)
@staticmethod
def _build_echo_parser() -> cmd2.Cmd2ArgumentParser:
"""Parser factory method for use with the echo command."""
echo_parser = cmd2.Cmd2ArgumentParser(description="Command that echoes input.")
echo_parser.add_argument("-u", "--upper", action="store_true", help="uppercase the output")
echo_parser.add_argument("-r", "--repeat", type=int, default=1, help="output [n] times")
echo_parser.add_argument("words", nargs="+", help="words to print")
return echo_parser
@cmd2.with_argparser(_build_echo_parser)
def do_echo(self, args: argparse.Namespace) -> None:
"""Command using with_argparser decorator for parsing arguments."""
output_str = " ".join(args.words)
if args.upper:
output_str = output_str.upper()
for _ in range(args.repeat):
self.poutput(
stylize(
output_str,
style=Style(color=self.foreground_color),
)
)
if __name__ == "__main__":
app = BasicApp()
sys.exit(app.cmdloop())
Cmd class initializer
A cmd2.Cmd instance or subclass instance is an interactive CLI application framework. There is no good reason to instantiate Cmd itself; rather, it's useful as a superclass of a class you define yourself in order to inherit Cmd's methods and encapsulate action methods.
Certain things must be initialized within the __init__() method of your class derived from cmd2.Cmd(all arguments to __init__() are optional):
cmd2.Cmd.__init__
__init__(
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,
)
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
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 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 | |
Cmd class variables
The cmd2.Cmd class provides several class-level variables that can be overridden in subclasses to change default behavior across all instances of that class.
- DEFAULT_CATEGORY: The default help category for commands defined in the class which haven't been explicitly categorized. (Default:
"Cmd2 Commands") - DEFAULT_EDITOR: The default editor program used by the
editcommand. - DEFAULT_PROMPT: The default prompt string. (Default:
"(Cmd) ") - MISC_HEADER: Header for the help section listing miscellaneous help topics. (Default:
"Miscellaneous Help Topics")
Cmd instance attributes
The cmd2.Cmd class provides a large number of public instance attributes which allow developers to customize a cmd2 application further beyond the options provided by the __init__() method.
Public instance attributes
Here are instance attributes of cmd2.Cmd which developers might wish to override:
- broken_pipe_warning: if non-empty, this string will be displayed if a broken pipe error occurs
- continuation_prompt: used for multiline commands on 2nd+ line of input
- debug: if
True, show full stack trace on error (Default:False) - default_error: the error that prints when a non-existent command is run
- disabled_commands: commands that have been disabled from use. This is to support commands that are only available during specific states of the application. This dictionary's keys are the command names and its values are DisabledCommand objects.
- echo: if
True, each command the user issues will be repeated to the screen before it is executed. This is particularly useful when running scripts. This behavior does not occur when running a command at the prompt. (Default:False) - editor: text editor program to use with edit command (e.g.
vim) - exclude_from_history: commands to exclude from the history command
- exit_code: this determines the value returned by
cmdloop()when exiting the application - help_error: the error that prints when no help information can be found
- hidden_commands: commands to exclude from the help menu and tab completion
- last_result: stores results from the last command run to enable usage of results in a Python script or interactive console. Built-in commands don't make use of this. It is purely there for user-defined commands and convenience.
- macros: dictionary of macro names and their values
- max_column_completion_results: The maximum number of completion results to display in a single column (Default: 7)
- max_completion_table_items: The maximum number of completion results allowed for a completion table to appear (Default: 50)
- pager: sets the pager command used by the
Cmd.ppaged()method for displaying wrapped output using a pager - pager_chop: sets the pager command used by the
Cmd.ppaged()method for displaying chopped/truncated output using a pager - py_bridge_name: name by which embedded Python environments and scripts refer to the
cmd2application by in order to call commands (Default:app) - py_locals: dictionary that defines specific variables/functions available in Python shells and scripts (provides more fine-grained control than making everything available with self_in_py)
- quiet: if
True, then completely suppress nonessential output (Default:False) - scripts_add_to_history: if
True, scripts and pyscripts add commands to history (Default:True) - self_in_py: if
True, allow access to your application in py command viaself(Default:False) - settable: dictionary that controls which of these instance attributes are settable at runtime using the set command
- timing: if
True, display execution time for each command (Default:False)