cmd2 is a powerful Python library for quickly building feature-rich and user-friendly interactive command-line applications. It extends Python's built-in `cmd` module, providing a comprehensive set of enhancements including robust tab completion, searchable command history, text and Python scripting, and advanced argument parsing with `argparse`. The library is actively maintained with a frequent release cadence, continuously improving its capabilities and user experience.
pip install cmd2Verified import paths — ran on the pinned version, not inferred.
This minimal example demonstrates how to create a basic `cmd2` application by subclassing `cmd2.Cmd` and defining a `do_` method for a command. Running `cmdloop()` starts the interactive shell, and you can type `hello_world` or `quit` to exit.
Review the official 'Migration Guide' for upgrading from 2.x to 3.x in the cmd2 documentation. Adapt custom completer/choices_provider functions to return the new object types.
Ensure your project uses Python 3.10 or higher to be compatible with current `cmd2` versions.
Avoid using `Cmd.cmdqueue`. `cmd2` provides alternative mechanisms for running commands via `cmdloop()`, text scripts, Python scripts, and history replays, which offer more consistent behavior.
If you require custom behavior for empty lines, you will need to implement a post-parsing hook or similar mechanism to detect and handle them manually.
Migrate from `py run()` to the `pyscript` command for executing Python scripts within your `cmd2` application.
Run `pip install cmd2` in your terminal to install the library.
Ensure the method or attribute you are trying to access exists in your `cmd2` version. For path completion with `argparse` decorators, utilize the `choices_provider` parameter of `parser.add_argument()` and pass `cmd2.Cmd.path_complete` to it.
When programmatically executing commands and needing to control history, use `app.onecmd_plus_hooks(command_string, add_to_history=True)` instead of directly calling `onecmd()`.
To gracefully handle `argparse` errors within `cmd2` commands, catch `SystemExit` and re-raise `cmd2.exceptions.Cmd2ArgparseError` within your command method. This allows `cmd2` to display the error message without exiting the application.