Knack CLI Framework

0.13.0 · active · verified Thu Apr 09

Knack is a lightweight Python framework for building command-line interfaces (CLIs) with a focus on ease of use and extensibility. It provides common CLI features like command grouping, argument parsing, help generation, and output formatting. The current version is 0.13.0, with new releases typically tied to Python version support and bug fixes, occurring a few times a year.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic Knack CLI with a single command group and command. It defines a command loader, registers a simple 'hello' command, and then invokes the CLI programmatically. Save this as a Python file and run it directly to see the output.

import sys
from knack.cli import CLI
from knack.commands import CLICommandsLoader

# Define a simple command handler
def hello_command_handler():
    """Says hello."""
    print("Hello from Knack CLI!")
    return 0

# Define a custom commands loader
class MyCommandsLoader(CLICommandsLoader):
    def load_command_table(self, args):
        # Define a command group 'greet' and a command 'hello' within it
        with self.command_group('greet', operations_tmpl='{}#{{}}'.format(__name__)) as g:
            g.command('hello', 'hello_command_handler')
        return self.command_table

# Create the CLI instance
mycli = CLI(cli_name='mycli', commands_loader_cls=MyCommandsLoader)

if __name__ == '__main__':
    # Example of invoking the CLI programmatically.
    # For actual command-line use, you'd typically pass sys.argv[1:].
    # To run this example: python your_script.py
    print("\n--- Invoking 'mycli greet hello' ---")
    exit_code = mycli.invoke(['greet', 'hello'])
    print(f"CLI exited with code: {exit_code}")

    print("\n--- Invoking 'mycli --help' ---")
    exit_code = mycli.invoke(['--help'])
    print(f"CLI exited with code: {exit_code}")

view raw JSON →