### Basic cmd2 Application Setup (Python) Source: https://github.com/python-cmd2/cmd2/blob/main/docs/examples/getting_started.md This snippet demonstrates the fundamental structure for creating a basic cmd2 application. It involves subclassing cmd2.Cmd and initiating the command loop. This is the entry point for any cmd2-based application. ```python #!/usr/bin/env python """A basic cmd2 application.""" import cmd2 class BasicApp(cmd2.Cmd): """Cmd2 application to demonstrate many common features.""" if __name__ == '__main__': import sys app = BasicApp() sys.exit(app.cmdloop()) ``` -------------------------------- ### Basic cmd2 Application Initialization Example Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/initialization.md This Python code snippet demonstrates a basic cmd2 application, showcasing various capabilities that can be utilized during the initialization process. It serves as a starting point for building interactive command-line interfaces with cmd2. ```python from cmd2 import Cmd class MyCmdApp(Cmd): """A sample cmd2 application.""" def __init__(self): super().__init__() # Initialize custom attributes or settings here self.my_custom_setting = "initial_value" # Define commands here def do_greet(self, arg): """Greet the user.""" print(f"Hello, {arg}!") if __name__ == '__main__': app = MyCmdApp() app.cmdloop() ``` -------------------------------- ### Install cmd2 from Debian/Ubuntu repositories Source: https://github.com/python-cmd2/cmd2/blob/main/docs/overview/installation.md Installs cmd2 from the Debian or Ubuntu package repositories using apt-get. This method is an alternative to using pip. ```shell $ sudo apt-get install python3-cmd2 ``` -------------------------------- ### Install cmd2 from GitHub using pip Source: https://github.com/python-cmd2/cmd2/blob/main/docs/overview/installation.md Installs the latest development version of cmd2 directly from its GitHub repository using pip. This command also upgrades the package if it's already installed. ```shell $ pip install -U git+git://github.com/python-cmd2/cmd2.git ``` -------------------------------- ### Upgrade pip and setuptools on Linux/macOS Source: https://github.com/python-cmd2/cmd2/blob/main/docs/overview/installation.md Upgrades pip and setuptools to their latest versions on Linux and macOS systems. These are prerequisites for installing Python packages. ```shell $ pip install -U pip setuptools ``` -------------------------------- ### Install cmd2 using pip Source: https://github.com/python-cmd2/cmd2/blob/main/docs/overview/installation.md Installs the cmd2 package and its dependencies from PyPI using pip. This is the recommended installation method. ```shell $ pip install cmd2 ``` -------------------------------- ### Upgrade pip and setuptools on Windows Source: https://github.com/python-cmd2/cmd2/blob/main/docs/overview/installation.md Upgrades pip and setuptools to their latest versions on Windows systems using the python -m pip command. These are prerequisites for installing Python packages. ```shell C:\> python -m pip install -U pip setuptools ``` -------------------------------- ### Example of cmd2 Shell Command Shortcut Source: https://github.com/python-cmd2/cmd2/blob/main/docs/examples/getting_started.md This example illustrates the usage of a shortcut in the cmd2 shell. Instead of typing the full 'shell' command followed by the shell command (e.g., 'shell ls -al'), users can utilize a predefined shortcut, such as '!', to achieve the same result ('!ls -al'). This simplifies command entry for frequently used shell commands. ```shell (Cmd) shell ls -al ``` ```shell (Cmd) !ls -al ``` -------------------------------- ### Basic cmd2 'Hello World' application Source: https://github.com/python-cmd2/cmd2/blob/main/README.md A simple 'Hello World' application built with cmd2. It defines a command 'hello_world' that outputs the string 'Hello World'. This example demonstrates the basic structure of a cmd2 application. ```python #!/usr/bin/env python """A simple cmd2 application.""" import cmd2 class FirstApp(cmd2.Cmd): """A simple cmd2 application.""" def do_hello_world(self, _: cmd2.Statement): self.poutput('Hello World') if __name__ == '__main__': import sys c = FirstApp() sys.exit(c.cmdloop()) ``` -------------------------------- ### Example of Multiline Command Input in cmd2 Source: https://github.com/python-cmd2/cmd2/blob/main/docs/examples/getting_started.md This example demonstrates how to input a multiline command in cmd2. The 'orate' command, configured for multiline input, accepts text spanning several lines. The prompt changes to indicate ongoing input, and the command is executed only when an unquoted semicolon is encountered, signifying the end of the input. ```text (Cmd) orate O for a Muse of fire, that would ascend > The brightest heaven of invention, > A kingdom for a stage, princes to act > And monarchs to behold the swelling scene! ; ``` -------------------------------- ### Set Command Usage Example Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/builtin_commands.md The 'set' command allows users to view and modify application settings. This example demonstrates how to change the 'allow_style' setting. ```shell (Cmd) set allow_style Never ``` -------------------------------- ### Install cmd2 using pip Source: https://github.com/python-cmd2/cmd2/blob/main/README.md Installs the latest stable version of the cmd2 library using pip. This command is compatible with all operating systems and requires Python 3.10+. ```bash pip install -U cmd2 ``` -------------------------------- ### Python: Initialize Mixin and cmd2.Cmd Application Source: https://github.com/python-cmd2/cmd2/blob/main/docs/mixins/mixin_template.md Demonstrates how to create a mixin class and an example application that uses it. The initialization order is crucial: the mixin must be inherited before cmd2.Cmd to ensure proper initialization and method resolution. ```python class MyMixin: def __init__(self, *args, **kwargs): # code placed here runs before cmd2.Cmd initializes super().__init__(*args, **kwargs) # code placed here runs after cmd2.Cmd initializes import cmd2 class Example(MyMixin, cmd2.Cmd): """A cmd2 application class to show how to use a mixin class.""" def __init__(self, *args, **kwargs): # code placed here runs before cmd2.Cmd or # any mixins initialize super().__init__(*args, **kwargs) # code placed here runs after cmd2.Cmd and # all mixins have initialized ``` -------------------------------- ### Initialize cmd2 Application Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/hooks.md The standard method for starting a cmd2 application involves creating a class that inherits from cmd2.Cmd and then instantiating and running its command loop. ```python import cmd2 class App(cmd2.Cmd): # customized attributes and methods here if __name__ == '__main__': app = App() app.cmdloop() ``` -------------------------------- ### Instantiate and Run cmd2 App Source: https://github.com/python-cmd2/cmd2/blob/main/docs/index.md Shows the process of instantiating a cmd2 application subclass and starting its command loop. This is the fundamental step to make the CLI interactive. The code requires the cmd2 package and a defined App class. ```python from cmd2 import Cmd class App(Cmd): # customized attributes and methods here app = App() app.cmdloop() ``` -------------------------------- ### Install cmd2 with administrator privileges Source: https://github.com/python-cmd2/cmd2/blob/main/docs/overview/installation.md Installs the cmd2 package using pip with administrator or root privileges, necessary in some environments. Replace '' with 'cmd2'. ```shell $ sudo pip install ``` -------------------------------- ### Shell Command Example Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/builtin_commands.md The 'shell' command executes a command as if it were run from the operating system's shell prompt. This example shows how to run 'pwd -P'. ```shell (Cmd) shell pwd -P /usr/local/bin ``` -------------------------------- ### Basic cmd2 Application Structure in Python Source: https://context7.com/python-cmd2/cmd2/llms.txt Demonstrates the fundamental structure of a cmd2 application by subclassing cmd2.Cmd and defining 'do_*' methods for commands. This example includes a 'greet' command and a 'quit' command to exit the application. ```python #!/usr/bin/env python """A simple cmd2 application.""" import cmd2 class MyApp(cmd2.Cmd): """A simple cmd2 application.""" def __init__(self): super().__init__() self.intro = 'Welcome to MyApp. Type help or ? to list commands.' def do_greet(self, statement: cmd2.Statement) -> None: """Greet the user with an optional name.""" name = statement.args or 'World' self.poutput(f'Hello, {name}!') def do_quit(self, _: cmd2.Statement) -> bool: """Exit the application.""" self.poutput('Goodbye!') return True # Returning True exits the command loop if __name__ == '__main__': import sys app = MyApp() sys.exit(app.cmdloop()) ``` -------------------------------- ### Python Cmd2 Scripting API Example Source: https://context7.com/python-cmd2/cmd2/llms.txt Demonstrates how to enable Python scripting in a cmd2 application. It defines custom commands like 'create' and 'complete' that return structured data, accessible by external Python scripts via the `app()` bridge. This allows for powerful automation of command-line interfaces. ```python #!/usr/bin/env python """Example cmd2 application with scripting support.""" import cmd2 from cmd2 import Cmd2ArgumentParser, with_argparser from dataclasses import dataclass @dataclass(frozen=True) class TaskResult: """Immutable result object for scripting.""" task_id: str status: str message: str class ScriptableApp(cmd2.Cmd): """Application designed for Python scripting.""" def __init__(self): super().__init__() self.tasks = {} self.py_bridge_name = 'app' # Access via app('command') in pyscripts create_parser = Cmd2ArgumentParser(description='Create a new task') create_parser.add_argument('name', help='task name') create_parser.add_argument('--priority', type=int, default=1, help='task priority (1-5)') @with_argparser(create_parser) def do_create(self, args) -> None: """Create a new task and return result for scripting.""" task_id = f'task-{len(self.tasks) + 1}' self.tasks[task_id] = { 'name': args.name, 'priority': args.priority, 'status': 'pending' } self.poutput(f'Created task: {task_id}') # Set last_result for script access self.last_result = TaskResult( task_id=task_id, status='created', message=f'Task "{args.name}" created successfully' ) complete_parser = Cmd2ArgumentParser(description='Complete a task') complete_parser.add_argument('task_id', help='task ID to complete') @with_argparser(complete_parser) def do_complete(self, args) -> None: """Mark a task as complete.""" if args.task_id in self.tasks: self.tasks[args.task_id]['status'] = 'completed' self.psuccess(f'Completed: {args.task_id}') self.last_result = TaskResult( task_id=args.task_id, status='completed', message='Task marked as complete' ) else: self.perror(f'Task not found: {args.task_id}') self.last_result = None if __name__ == '__main__': import sys app = ScriptableApp() sys.exit(app.cmdloop()) # Example pyscript (save as workflow.py and run with: run_pyscript workflow.py) """ # Create tasks result = app('create "Write documentation" --priority 2') if result: task1 = result.data print(f'Created: {task1.task_id}') result = app('create "Review code" --priority 3') if result: task2 = result.data print(f'Created: {task2.task_id}') # Complete first task result = app(f'complete {task1.task_id}') if result: print(f'Status: {result.data.message}') """ ``` -------------------------------- ### Create Subcommands with @as_subcommand_to in Python Source: https://context7.com/python-cmd2/cmd2/llms.txt This snippet demonstrates how to create commands with subcommands using argparse subparsers and the `@as_subcommand_to` decorator in Python. It defines a `DatabaseCLI` class with 'db add', 'db get', and 'db list' subcommands, managing records in a dictionary. Dependencies include the 'cmd2' and 'argparse' libraries. ```python import argparse import cmd2 from cmd2 import Cmd2ArgumentParser, with_argparser, as_subcommand_to class DatabaseCLI(cmd2.Cmd): """Database management CLI with subcommands.""" def __init__(self): super().__init__() self.records = {} # Main 'db' command parser with subparsers db_parser = Cmd2ArgumentParser(description='Database operations') db_subparsers = db_parser.add_subparsers(title='operation', help='database operation', required=True) # 'db add' subcommand parser add_parser = Cmd2ArgumentParser(description='Add a record') add_parser.add_argument('key', help='record key') add_parser.add_argument('value', help='record value') @as_subcommand_to('db', 'add', add_parser, help='add a new record') def db_add(self, args: argparse.Namespace) -> None: """Add a record to the database.""" self.records[args.key] = args.value self.psuccess(f'Added: {args.key} = {args.value}') # 'db get' subcommand parser get_parser = Cmd2ArgumentParser(description='Get a record') get_parser.add_argument('key', help='record key to retrieve') @as_subcommand_to('db', 'get', get_parser, help='retrieve a record') def db_get(self, args: argparse.Namespace) -> None: """Get a record from the database.""" if args.key in self.records: self.poutput(f'{args.key}: {self.records[args.key]}') self.last_result = self.records[args.key] else: self.perror(f'Key not found: {args.key}') # 'db list' subcommand parser list_parser = Cmd2ArgumentParser(description='List all records') @as_subcommand_to('db', 'list', list_parser, help='list all records') def db_list(self, _: argparse.Namespace) -> None: """List all records in the database.""" for key, value in self.records.items(): self.poutput(f'{key}: {value}') self.last_result = self.records.copy() @with_argparser(db_parser) def do_db(self, args: argparse.Namespace) -> None: """Database operations with subcommands.""" handler = args.cmd2_handler.get() if handler: handler(args) if __name__ == '__main__': import sys app = DatabaseCLI() sys.exit(app.cmdloop()) ``` -------------------------------- ### Initialize cmd2 with a Startup Script (Python) Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/startup_commands.md Demonstrates how to initialize a `cmd2.Cmd` application with a startup script by providing the script's file path to the `startup_script` argument. The script's commands will run after application initialization. ```python import cmd2 class StartupApp(cmd2.Cmd): def __init__(self): cmd2.Cmd.__init__(self, startup_script='.cmd2rc') ``` -------------------------------- ### Import argparse Module in Python Source: https://github.com/python-cmd2/cmd2/blob/main/docs/examples/getting_started.md This snippet shows the necessary import statement for the argparse module, which is used for command-line argument parsing in Python. ```python import argparse ``` -------------------------------- ### Define Multiline Command in cmd2 (Python) Source: https://github.com/python-cmd2/cmd2/blob/main/docs/examples/getting_started.md This Python code defines a 'speak' command and then creates an alias 'orate' for it, specifically to handle multiline input. The `__init__` method is modified to include 'orate' in the `multiline_commands` list, enabling cmd2 to recognize commands that span multiple lines and are terminated by a semicolon. ```python @cmd2.with_argparser(speak_parser) def do_speak(self, args): """Repeats what you tell me to.""" words = [] for word in args.words: if args.piglatin: word = '%s%say' % (word[1:], word[0]) if args.shout: word = word.upper() words.append(word) repetitions = args.repeat or 1 for _ in range(min(repetitions, self.maxrepeats)): # .poutput handles newlines, and accommodates output redirection too self.poutput(' '.join(words)) # orate is a synonym for speak which takes multiline input do_orate = do_speak ``` -------------------------------- ### Initialize cmd2 with a Silenced Startup Script (Python) Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/startup_commands.md Shows how to initialize a `cmd2.Cmd` application with a startup script while silencing its output by setting `silence_startup_script` to `True`. Note that `stderr` output will still be visible, and silencing requires `allow_redirection` to be `True`. ```python import cmd2 class StartupApp(cmd2.Cmd): def __init__(self): cmd2.Cmd.__init__(self, startup_script='.cmd2rc', silence_startup_script=True) ``` -------------------------------- ### Define Argument Parser and Command Logic for 'speak' in Python Cmd2 Source: https://github.com/python-cmd2/cmd2/blob/main/docs/examples/getting_started.md This snippet defines an argument parser for the 'speak' command using cmd2.Cmd2ArgumentParser and implements the command's logic in the do_speak method. It handles options for Pig Latin, shouting, and repeating output, and uses self.poutput for displaying results. ```python speak_parser = cmd2.Cmd2ArgumentParser() speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay') speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE') speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times') speak_parser.add_argument('words', nargs='+', help='words to say') @cmd2.with_argparser(speak_parser) def do_speak(self, args): """Repeats what you tell me to.""" words = [] for word in args.words: if args.piglatin: word = '%s%say' % (word[1:], word[0]) if args.shout: word = word.upper() words.append(word) repetitions = args.repeat or 1 for _ in range(min(repetitions, self.maxrepeats)): # .poutput handles newlines, and accommodates output redirection too self.poutput(' '.join(words)) ``` -------------------------------- ### Adding a Settable Parameter to cmd2 Application (Python) Source: https://github.com/python-cmd2/cmd2/blob/main/docs/examples/getting_started.md This code illustrates how to add a new settable parameter ('maxrepeats') to a cmd2 application. It involves overriding the __init__ method, initializing the superclass, defining the parameter attribute, and registering it using add_settable. This allows users to configure application behavior at runtime. ```python def __init__(self): super().__init__() # Make maxrepeats settable at runtime self.maxrepeats = 3 self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self)) ``` -------------------------------- ### Execute Build Command and Get Status via PyScript Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/scripting.md This Python script interacts with a cmd2 application that has 'build' and 'status' commands. It first calls the 'build' command to start a process and then retrieves the returned `BuildStatus` object. It checks for errors and prints the build name and status, demonstrating how scripts can consume complex data returned by cmd2 commands. ```python import sys import time # start build result = app('build tower') # If there was an error then exit if not result: print('Build failed') sys.exit() # This is a BuildStatus dataclass object build = result.data print(f"Build {build.name} : {build.status}") ``` -------------------------------- ### Mixin and Initialize a cmd2 Plugin Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/plugins.md Demonstrates how to create a plugin as a mixin class and initialize it within a cmd2 application. The order of inheritance is crucial for proper initialization. ```python class MyPlugin: def __init__(self, *args, **kwargs): # code placed here runs before cmd2.Cmd initializes super().__init__(*args, **kwargs) # code placed here runs after cmd2.Cmd initializes class Example(MyPlugin, cmd2.Cmd): """An class to show how to use a plugin""" def __init__(self, *args, **kwargs): # code placed here runs before cmd2.Cmd or # any plugins initialize super().__init__(*args, **kwargs) # code placed here runs after cmd2.Cmd and # all plugins have initialized ``` -------------------------------- ### Add Shortcut to cmd2 Application (Python) Source: https://github.com/python-cmd2/cmd2/blob/main/docs/examples/getting_started.md This Python code snippet demonstrates how to add a custom shortcut for the 'speak' command in a cmd2 application. It involves updating the default shortcuts dictionary within the `__init__` method. This allows users to trigger the 'speak' command using a single character, like '&', instead of typing the full command name. ```python def __init__(self): shortcuts = cmd2.DEFAULT_SHORTCUTS shortcuts.update({'&': 'speak'}) super().__init__(shortcuts=shortcuts) # Make maxrepeats settable at runtime self.maxrepeats = 3 self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self)) ``` -------------------------------- ### Enable Multiline Commands in cmd2 Initializer (Python) Source: https://github.com/python-cmd2/cmd2/blob/main/docs/examples/getting_started.md This Python code snippet shows how to configure cmd2 to recognize specific commands as multiline. By passing a list of command names to the `multiline_commands` parameter in the `super().__init__()` call, the application can handle inputs that span multiple lines, using a defined terminator (like a semicolon) to signal the end of the command. ```python super().__init__(multiline_commands=['orate'], shortcuts=shortcuts) ``` -------------------------------- ### Displaying Help for All Commands in cmd2 Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/help.md The built-in 'help' command in cmd2, when used without arguments, displays a list of all documented commands available in the application. This provides users with an overview of the application's capabilities. ```text (Cmd) help Documented Commands ─────────────────── alias help ipy py run_pyscript set shortcuts edit history macro quit run_script shell ``` -------------------------------- ### Displaying Detailed Help for a Specific Command in cmd2 Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/help.md Users can obtain detailed help for a specific command by appending the command name to the 'help' command. This displays the command's usage, description, and any optional arguments. ```text (Cmd) help quit Usage: quit [-h] Exit this application. Optional Arguments: -h, --help show this help message and exit ``` -------------------------------- ### Styled Terminal Output with Rich Integration in Python Source: https://context7.com/python-cmd2/cmd2/llms.txt Demonstrates using cmd2's output methods with the Rich library for styled terminal output. It includes examples for displaying data in tables, text within panels, styled text, and various output levels (success, warning, error). Dependencies include cmd2 and Rich. Input is typically command-line arguments or internal data structures. Output is styled terminal text. ```python import cmd2 from rich.table import Table from rich.panel import Panel from rich.text import Text from cmd2.colors import Color class StyledApp(cmd2.Cmd): """Application demonstrating styled output with Rich.""" def __init__(self): super().__init__() self.data = [ {'name': 'Alice', 'role': 'Developer', 'level': 3}, {'name': 'Bob', 'role': 'Designer', 'level': 2}, {'name': 'Charlie', 'role': 'Manager', 'level': 4}, ] def do_table(self, _: cmd2.Statement) -> None: """Display data in a Rich table.""" table = Table(title='Team Members', show_header=True) table.add_column('Name', style=Color.CYAN) table.add_column('Role', style=Color.GREEN) table.add_column('Level', justify='right', style=Color.YELLOW) for person in self.data: table.add_row( person['name'], person['role'], str(person['level']) ) self.poutput(table) def do_panel(self, statement: cmd2.Statement) -> None: """Display text in a Rich panel.""" content = statement.args or 'Hello, World!' panel = Panel(content, title='Message', border_style=Color.BLUE) self.poutput(panel) def do_styled(self, _: cmd2.Statement) -> None: """Show styled text examples.""" text = Text() text.append('Success: ', style=Color.GREEN) text.append('Operation completed\n') text.append('Warning: ', style=Color.YELLOW) text.append('Low disk space\n') text.append('Error: ', style=Color.RED) text.append('File not found') self.poutput(text) def do_status(self, statement: cmd2.Statement) -> None: """Demonstrate different output methods.""" message = statement.args or 'Test message' self.poutput(f'Normal: {message}') self.psuccess(f'Success: {message}') self.pwarning(f'Warning: {message}') self.perror(f'Error: {message}') self.pfeedback(f'Feedback: {message}') if __name__ == '__main__': import sys app = StyledApp() sys.exit(app.cmdloop()) ``` -------------------------------- ### Commenting in cmd2 Command Scripts Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/scripting.md Lines starting with '#' are treated as comments. This applies to the first non-whitespace character. ```cmd2 (Cmd) # This is a comment (Cmd) command # This is not a comment ``` -------------------------------- ### Create New Settable Parameters in Python Source: https://github.com/python-cmd2/cmd2/blob/main/docs/features/settings.md Defines user-settable parameters by creating an instance attribute, a Settable object describing the setting, and adding it to the cmd2 application. Optionally, a callback can be provided to be notified when a setting changes. ```python class MyApp(cmd2.Cmd): def __init__(self): super().__init__() # 1. Create an instance attribute with a default value self.sunny = False # 2. Create a Settable object which describes your setting sunny_setting = cmd2.utils.Settable( cmd2.settings.Setting( 'sunny', self.sunny, bool, "Is it sunny outside?", ), onchange_cb=self.on_setting_change ) # 3. Pass the Settable object to the add_settable method self.add_settable(sunny_setting) def on_setting_change(self, setting, old_value, new_value): """Callback function called when a setting changes.""" self.poutput(f"{setting.name} - was: {old_value}") self.poutput(f"now: {new_value}") # ... other methods ... if __name__ == '__main__': app = MyApp() app.cmdloop() ``` -------------------------------- ### Uninstall cmd2 using pip Source: https://github.com/python-cmd2/cmd2/blob/main/docs/overview/installation.md Uninstalls the cmd2 package from the system using pip. This command removes the package and its associated files. ```shell $ pip uninstall cmd2 ```