Initialization
Here is a basic example cmd2
application which demonstrates many capabilities which you may wish to utilize while initializing the app:
#!/usr/bin/env python3
# coding=utf-8
"""A simple example cmd2 application demonstrating the following:
1) Colorizing/stylizing output
2) Using multiline commands
3) Persistent history
4) How to run an initialization script at startup
5) How to group and categorize commands when displaying them in help
6) Opting-in to using the ipy command to run an IPython shell
7) Allowing access to your application in py and ipy
8) Displaying an intro banner upon starting your application
9) Using a custom prompt
10) How to make custom attributes settable at runtime
"""
import cmd2
from cmd2 import (
Bg,
Fg,
style,
)
class BasicApp(cmd2.Cmd):
CUSTOM_CATEGORY = 'My Custom Commands'
def __init__(self):
super().__init__(
multiline_commands=['echo'],
persistent_history_file='cmd2_history.dat',
startup_script='scripts/startup.txt',
include_ipy=True,
)
# Prints an intro banner once upon application startup
self.intro = style('Welcome to cmd2!', fg=Fg.RED, bg=Bg.WHITE, bold=True)
# Show this as the prompt when asking for input
self.prompt = 'myapp> '
# Used as prompt for multiline commands after the first line
self.continuation_prompt = '... '
# Allow access to your application in py and ipy via self
self.self_in_py = True
# Set the default category name
self.default_category = 'cmd2 Built-in Commands'
# Color to output text in with echo command
self.foreground_color = Fg.CYAN.name.lower()
# Make echo_fg settable at runtime
fg_colors = [c.name.lower() for c in Fg]
self.add_settable(
cmd2.Settable('foreground_color', str, 'Foreground color to use with echo command', self,
choices=fg_colors)
)
@cmd2.with_category(CUSTOM_CATEGORY)
def do_intro(self, _):
"""Display the intro banner"""
self.poutput(self.intro)
@cmd2.with_category(CUSTOM_CATEGORY)
def do_echo(self, arg):
"""Example of a multiline command"""
fg_color = Fg[self.foreground_color.upper()]
self.poutput(style(arg, fg=fg_color))
if __name__ == '__main__':
app = BasicApp()
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='tab', stdin=None, stdout=None, *, persistent_history_file='', persistent_history_length=1000, startup_script='', silence_startup_script=False, include_py=False, include_ipy=False, allow_cli_args=True, transcript_files=None, allow_redirection=True, multiline_commands=None, terminators=None, shortcuts=None, command_sets=None, auto_load_commands=True, allow_clipboard=True, suggest_similar_command=False)
An easy but powerful framework for writing line-oriented command interpreters. Extends Python's cmd package.
PARAMETER | DESCRIPTION |
---|---|
completekey
|
readline name of a completion key, default to Tab
TYPE:
|
stdin
|
alternate input file object, if not specified, sys.stdin is used
TYPE:
|
stdout
|
alternate output file object, if not specified, sys.stdout is used
TYPE:
|
persistent_history_file
|
file path to load a persistent cmd2 command history from
TYPE:
|
persistent_history_length
|
max number of history items to write to the persistent history file
TYPE:
|
startup_script
|
file path to a script to execute at startup
TYPE:
|
silence_startup_script
|
if
TYPE:
|
include_py
|
should the "py" command be included for an embedded Python shell
TYPE:
|
include_ipy
|
should the "ipy" command be included for an embedded IPython shell
TYPE:
|
allow_cli_args
|
if
TYPE:
|
transcript_files
|
pass a list of transcript files to be run on initialization. This allows running transcript tests when
TYPE:
|
allow_redirection
|
If
TYPE:
|
multiline_commands
|
list of commands allowed to accept multi-line input
TYPE:
|
terminators
|
list of characters that terminate a command. These are mainly intended for terminating multiline commands, but will also terminate single-line commands. If not supplied, the default is a semicolon. If your app only contains single-line commands and you want terminators to be treated as literals by the parser, then set this to an empty list.
TYPE:
|
shortcuts
|
dictionary containing shortcuts for commands. If not supplied, then defaults to constants.DEFAULT_SHORTCUTS. If you do not want any shortcuts, pass an empty dictionary.
TYPE:
|
command_sets
|
Provide CommandSet instances to load during cmd2 initialization. This allows CommandSets with custom constructor parameters to be loaded. This also allows the a set of CommandSets to be provided when
TYPE:
|
auto_load_commands
|
If True, cmd2 will check for all subclasses of
TYPE:
|
allow_clipboard
|
If False, cmd2 will disable clipboard interactions
TYPE:
|
suggest_similar_command
|
If
TYPE:
|
Source code in cmd2/cmd2.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 |
|
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 override:
- always_show_hint: if
True
, display tab completion hint even when completion suggestions print (Default:False
) - 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_category: if any command has been categorized, then all other commands that haven't been categorized will display under this section in the help output.
- default_error: the error that prints when a non-existent command is run
- default_sort_key: the default key for sorting string results. Its default value performs a case-insensitive alphabetical sort.
- default_to_shell: if
True
, attempt to run unrecognized commands as shell commands (Default:False
) - 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.
- doc_header: Set the header used for the help function's listing of documented functions
- 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 - feedback_to_output: if
True
, send nonessential output to stdout, ifFalse
send them to stderr (Default:False
) - 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_completion_items: max number of CompletionItems to display during tab completion (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
cmd2
application 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
)