Knack CLI Framework
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
- breaking Knack frequently drops support for older Python versions. Ensure your environment uses a currently supported Python version.
- breaking The internal handling of `bool` default values for arguments changed, which might affect argument parsing logic.
- gotcha The `colorama` dependency, used for ANSI escape sequences, became conditionally installed only on Windows.
Install
-
pip install knack
Imports
- CLI
from knack.cli import CLI
- CLICommandsLoader
from knack.commands import CLICommandsLoader
Quickstart
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}")