Module
clak
Clak: A Command Line Application Kit.
Clak is a framework for building command line applications in Python. It extends and enhances Python's argparse with features like:
- Simplified parser composition and inheritance
- Rich command completion support
- XDG Base Directory path flags and config-file loading (
XDGConfFileMixin,XDGDataDirMixin,XDGCacheDirMixin,XDGLogDirMixin) - Structured logging configuration
- Recursive subcommand handling
Canonical public API (import from clak):
- Parser: root/command class (auto-dispatches on init unless parse=False)
- Argument: positional or optional argument descriptor
- Arg / Opt: optional sugar for positionals vs flags (Argument still accepts both)
- Command: nested subcommand descriptor (SubParser is the class name)
Optional mixins (also from clak): ApiServerMixin, ApiEndpointMixin, LoggingOptMixin, RuntimeOptMixin, RichHelpMixin, LongHelpMixin,
Show/List/Pprint/Raw/Markdown/Rst/Data/CompositeViewMixin, completion,
XDGConfFileMixin / XDGDataDirMixin / XDGCacheDirMixin / XDGLogDirMixin,
WorkDirMixin.
Secondary entry points: clak.exception, clak.views (view classes),
clak.comp (mixins). Internal layout: clak.core, clak.runtime,
clak.views, clak.comp.
ApiEndpointMixin
ApiServeCmd
Bases: Parser
Start the HTTP API server (parent app must use ApiServerMixin).
Source code in clak/comp/api.py
ApiServerMixin
Root mixin: route discovery, request execution, server start.
Source code in clak/comp/api.py
api_app(auth=None, docs=None)
Build the backend app (useful for tests or external servers).
Source code in clak/comp/api.py
api_auth(user=None, password=None)
Credentials from arguments or Meta; None disables auth.
Source code in clak/comp/api.py
api_call(route, body)
Run one command and return JSON-able data (raises ApiError).
Source code in clak/comp/api.py
api_routes()
Endpoints below this node (commands including ApiEndpointMixin).
Source code in clak/comp/api.py
api_serve(host=None, port=None, auth=None, docs=None)
Start the server (blocking).
Source code in clak/comp/api.py
Arg
Bases: Argument
Optional sugar for a positional argument.
Same *args / **kwargs as :class:Argument, but at least one
positional name is required (no leading -). Empty Arg() is
rejected; dest-derived flags belong on Opt / Argument.
Argument still accepts both positionals and flags.
Source code in clak/core/descriptors.py
Argument
Bases: ArgParseItem
Represents an argument that can be added to an argument parser.
Handles both positional arguments and optional flags, choosing the
appropriate argparse form from the flag names. Optional helpers
:class:Arg (positionals) and :class:Opt (flags) reject mixed names.
Most keyword arguments are passed through to
:meth:argparse.ArgumentParser.add_argument. Clak-only kwargs (stripped
before argparse):
argument_group/option_group: Optional title for a help section (parser.add_argument_group). Same title reuses one section; pick the name that matches what you are grouping. Do not set both on one Argument.exclusive_group: Shared key for argparse mutual exclusion (add_mutually_exclusive_group). Same key reuses one XOR set (required=False). May nest under a help section when a help-group kwarg is also set.help_level:"main"(default) or"advanced". Advanced flags are summarized in short--helpand listed by--help-all.propagate: Copy this flag onto descendant parsers (default True). Set False to keep it on this parser only.
Source code in clak/core/descriptors.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | |
attach_arg_to_parser(key, config, attach_overrides=None)
Create and add an argument to the parser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The argument key/name |
required |
config
|
ParserNode
|
The parser configuration object |
required |
attach_overrides
|
dict
|
Kwargs applied only to this attach (not stored on the shared Argument descriptor). |
None
|
Returns:
| Type | Description |
|---|---|
Action
|
argparse.Action: The created argument parser action |
Source code in clak/core/descriptors.py
flag_strings(dest)
Option strings for a flag Argument, or empty if it is positional.
Source code in clak/core/descriptors.py
propagates()
suppress_attach_overrides(extra=None)
Attach-time overrides so a copy does not overwrite an outer dest.
Do not set required unless the source flag is required: some argparse actions reject the required= keyword.
Source code in clak/core/descriptors.py
with_kwargs(**overrides)
Return a shallow copy with overrides merged into kwargs.
Keeps args and the destination; the original is left untouched.
Source code in clak/core/descriptors.py
CompCmdRender
Bases: CompRenderCmdMixin, Parser
Command completion renderer class.
Combines the CompRenderCmdMixin with the base Parser to create a class that can render command completion code. This class provides the core functionality for generating shell completion scripts for command-line tools.
Key features: - Generates shell completion code for bash/tcsh/fish - Supports external completion scripts - Configurable executable names - Default completion behavior
Source code in clak/comp/completion.py
CompRenderCmdMixin
Bases: CompRenderMixin
Completion command support
Source code in clak/comp/completion.py
cli_run(ctx, **kwargs)
Command completion support mixin.
Adds command completion support to parsers by providing arguments to configure shell completion behavior:
- --no-defaults: Disable fallback to readline defaults (bash only)
- --complete-arguments: Custom completion arguments (bash only)
- --shell: Target shell (bash, zsh, tcsh, fish, powershell)
- --executable: Name of executable to complete
The mixin generates the appropriate shell completion code when run. Supports bash (default), zsh, tcsh, fish and powershell shells.
Example
my-app completion # Outputs bash completion code my-app completion --shell zsh # Outputs zsh completion code
Source code in clak/comp/completion.py
CompRenderOptMixin
Bases: CompRenderMixin
Completion options support mixin.
Adds a --completion flag that prints bash argcomplete shellcode
instead of running the command. Prefer :class:CompCmdRender as a
completion subcommand when you need --shell / --executable.
Example::
my-app --completion
Source code in clak/comp/completion.py
cli_run(ctx, **kwargs)
Print bash completion shellcode when --completion is set.
Example::
my-app --completion
Source code in clak/comp/completion.py
CompositeViewMixin
Bases: TextLayoutOptMixin, TableViewOptMixin
CLI flags for multi-section :class:~clak.views.CompositeView output.
Adds table options, --expand-keys, --format-scope, --width,
and --line-length. Does not set Meta.cli_view: return a
CompositeView(...) from cli_run. Table flags apply to the primary
section only. --line-length applies to text/pprint sections only.
--expand-keys is for a ListView primary; hide it with
Meta.view_cli_options when the primary is ShowView.
--format is table-scoped (view / yaml / json / csv);
markdown source is in --format-scope all envelopes, not --format raw.
Source code in clak/comp/views.py
DataViewMixin
Bases: _ViewMixinBase
Auto-render command results with :class:~clak.views.DataView.
Adds --format (json / yaml), --compact / --no-compact,
--color / --no-color, and --anchors / --no-anchors.
Syntax theme: Meta.view_syntax_theme or CLAK_SYNTAX_THEME, else
ansi_dark. Configure exposed flags with Meta.view_cli_options.
Source code in clak/comp/views.py
ListViewMixin
Bases: TableViewOptMixin
Auto-render command results with :class:~clak.views.ListView.
Adds --columns, --add-index / --no-add-index,
--expand-keys / --no-expand-keys, --format,
--sort-columns, --sort-mode, --width, and --wrap.
Configure exposed flags with Meta.view_cli_options.
Source code in clak/comp/views.py
LoggingOptMixin
Logging options support
Source code in clak/comp/logging.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 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 | |
assemble_user_config(configs)
Build cumulative verbosity tiers from Meta.log_levels.
Explicit entries use LEVEL|logger. Legacy configurations containing
only logger names are expanded to INFO and DEBUG tiers for each group.
Source code in clak/comp/logging.py
cli_hook__logging(instance, ctx, **_)
Inject or create logger into instance
Source code in clak/comp/logging.py
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 | |
select_user_config(user_config, req=0)
Select user config from requested level
Source code in clak/comp/logging.py
LongHelpMixin
-h prints the short help, --help the full one.
Replaces --help-all and --help-<topic>. Inherited by subcommands.
Source code in clak/comp/help.py
MarkdownViewMixin
Bases: TextViewOptMixin
Auto-render command results with :class:~clak.views.MarkdownView.
Adds --format (view / raw) and --line-length.
Syntax theme: Meta.view_syntax_theme or CLAK_SYNTAX_THEME, else
ansi_dark. Configure exposed flags with Meta.view_cli_options.
Source code in clak/comp/views.py
Opt
Bases: Argument
Optional sugar for an option flag.
Same *args / **kwargs as :class:Argument. When names are
given, every name must start with - / --. Empty Opt() is
allowed: the attribute name becomes a dest-derived flag (--attr
or -x). Argument still accepts both positionals and flags.
Source code in clak/core/descriptors.py
Parser
Bases: ParserNode
A simplified parser class that extends ParserNode.
This class provides a more streamlined interface to ParserNode by: - Automatically parsing arguments on initialization - Maintaining compatibility with legacy argument parser names - Providing simpler command/argument creation methods
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional arguments passed to ParserNode |
()
|
parse
|
bool
|
Whether to automatically parse arguments on init, only on root nodes |
True
|
**kwargs
|
Any
|
Keyword arguments passed to ParserNode |
{}
|
Source code in clak/core/parser.py
ParserNode
Bases: Node
An extensible argument parser that can be inherited to create custom CLIs.
This class provides a framework for building complex command-line interfaces with: - Hierarchical subcommands - Automatic help generation - Plugin support - Custom argument types - Exception handling
The parser can be extended by: 1. Subclassing and adding Argument instances as class attributes 2. Adding SubParser instances to create command hierarchies 3. Implementing cli_run() for command implementation 4. Implementing cli_group() for command group behavior
Attributes:
| Name | Type | Description |
|---|---|---|
children |
dict
|
Dictionary of subcommand name to child parser |
meta__name |
str
|
ParserNode name |
Source code in clak/core/parser.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 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 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | |
ctx
property
Last ClakContext from dispatch, or None before execute.
subparsers
property
Lazily create and return the subparsers object.
__init__(add_help=True, parent=None, name=None, key=None, parser=None, proc_name=None)
Initialize the parser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
add_help
|
bool
|
Whether to add help flags |
True
|
parent
|
ParserNode
|
Parent parser instance |
None
|
name
|
str
|
ParserNode name |
None
|
key
|
str
|
ParserNode key |
None
|
parser
|
ArgumentParser
|
Existing parser to use |
None
|
proc_name
|
str
|
Process name |
None
|
Source code in clak/core/parser.py
add_argument(key, arg=None, attach_overrides=None, **kwargs)
Add an argument to this parser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key/name for the argument |
required |
arg
|
Argument
|
The argument object to add |
None
|
attach_overrides
|
dict
|
Kwargs applied only to this attach |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to add_argument() |
{}
|
This method adds a new argument to the parser. The argument can be either a positional argument or an optional flag, determined by the Argument object.
Source code in clak/core/parser.py
add_arguments(arguments=None)
Initialize all argument options defined for this parser.
This method: 1. Collects arguments from meta__arguments_dict 2. Collects arguments defined as class attributes 3. Adds internal arguments like cli_self 4. Creates all argument parser entries 5. Copies ancestor flags onto this parser when inherit is on
Source code in clak/core/parser.py
add_subcommand(key, arg=None, **kwargs)
add_subcommands(subcommands=None)
Initialize all subcommands defined for this parser.
This method: 1. Collects subcommands from children dictionary 2. Collects Command instances defined as class attributes 3. Creates parser entries for all subcommands
Source code in clak/core/parser.py
clean_terminate(*args, **kwargs)
cli_execute(*args, **kwargs)
cli_exit(status=0, message=None)
Exit the CLI application with given status and message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
status
|
int
|
Exit status code |
0
|
message
|
str
|
Optional message to display |
None
|
Source code in clak/core/parser.py
cli_exit_error(message)
Exit the CLI application with an error message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message to display |
required |
cli_group(ctx, **_)
Execute group-level command behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
ClakContext
|
Command context object |
required |
**_
|
Any
|
Unused keyword arguments |
{}
|
cli_run(ctx, **kwargs)
Execute the command implementation.
This method should be overridden by subclasses to implement command behavior. The base implementation shows help for non-leaf nodes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
Any
|
Execution context |
required |
**kwargs
|
Any
|
Additional keyword arguments from command line |
{}
|
Raises:
| Type | Description |
|---|---|
ClakNotImplementedError
|
If leaf node has no implementation |
Source code in clak/core/parser.py
create_parser()
Create a new parser
Source code in clak/core/parser.py
dispatch(*args, **kwargs)
get_fname(attr='key')
get_help_formatter_class()
Return the legacy help_formatter marker class for this node.
Mixins set meta__help_formatter (or Meta.help_formatter).
Unset walks parents, then RichRecursiveHelpFormatter.
Source code in clak/core/parser.py
help_color_enabled()
True when --help is styled: help_color, else help_formatter.
Source code in clak/core/parser.py
help_texts(variables, first_line=False)
Return prepared (usage, description, epilog) for this node.
Reads Meta.help_usage / help_description (default: class
docstring) / help_epilog and formats them with variables.
first_line keeps only the description's first line (subcommands).
Source code in clak/core/parser.py
parse_args(*args, **kwargs)
show_help()
PprintViewMixin
Bases: TextLayoutOptMixin
Auto-render command results with :class:~clak.views.PprintView.
Adds --line-length. Configure exposed flags with Meta.view_cli_options.
Source code in clak/comp/views.py
RawViewMixin
Bases: TextLayoutOptMixin
Auto-render command results with :class:~clak.views.RawView.
Adds --line-length. Configure exposed flags with Meta.view_cli_options.
Source code in clak/comp/views.py
RecursiveHelpFormatter
Value for Meta.help_formatter selecting the plain (no color) layout.
Kept for compatibility: layout is produced by HelpRenderer and argparse
never sees this class. Prefer Meta.help_color = False.
Source code in clak/core/help_render.py
RichHelpMixin
Same default as Parser (Rich help formatter).
Optional. Useful to re-opt-in a child after a parent sets
Meta.help_color = False (or the legacy
Meta.help_formatter = RecursiveHelpFormatter).
Source code in clak/comp/help.py
RstViewMixin
Bases: TextViewOptMixin
Auto-render command results with :class:~clak.views.RstView.
Adds --format (view / raw) and --line-length.
Configure exposed flags with Meta.view_cli_options.
Source code in clak/comp/views.py
RuntimeOptMixin
--interactive, --no-input and -y/--yes flags.
Source code in clak/comp/runtime.py
cli_hook__runtime(instance, ctx, **_)
Resolve runtime flags and publish them on ctx.
Source code in clak/comp/runtime.py
ShowViewMixin
Bases: TableViewOptMixin
Auto-render command results with :class:~clak.views.ShowView.
Adds --columns, --add-index / --no-add-index,
--format, --sort-columns, --sort-mode, --width,
and --wrap.
Configure exposed flags with Meta.view_cli_options.
Source code in clak/comp/views.py
SubParser
Bases: ArgParseItem
Represents a subcommand parser that can be added to a parent parser.
This class handles creation of nested command structures, allowing for hierarchical
command-line interfaces via argparse add_subparsers.
Most keyword arguments are passed through to
:meth:argparse._SubParsersAction.add_parser. Clak-only kwargs (stripped
before argparse):
command_group: Optional key for a subcommand help section. Pair withMeta.command_groupson the parent Parser. Formatter metadata only; not a secondadd_subparsers. Commands with no key stay under leftoversubcommands:.
Source code in clak/core/descriptors.py
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 | |
attach_sub_to_parser(key, config)
Create a subcommand parser for this command.
Creates a new subparser for the command and configures it with the appropriate help text and options. Validates that the command name is valid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Name of the subcommand |
required |
config
|
ParserNode
|
Parent parser configuration object |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If command name contains spaces |
Returns:
| Name | Type | Description |
|---|---|---|
ParserNode |
ParserNode
|
The created child parser instance |
Source code in clak/core/descriptors.py
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 | |
WorkDirMixin
-W/--work-dir flag: run as if started in another directory.
Defaults to the current directory inherited from the parent process.
The resolved path is available as ctx.work_dir and
ctx.plugins["work_dir"].
Source code in clak/comp/config.py
XDGCacheDirMixin
XDGConfFileMixin
Bases: _XDGPathMixin
--conf-file flag and config-file loading.
Default: $XDG_CONFIG_HOME/<app>/config.yaml, where <app> comes
from Meta.app_name, else the parser name / class name.
Lookup order (first match wins, one file is loaded):
- explicit
--conf-file(relative paths resolve against the work dir) - first existing file from
Meta.config_local_namesin the work dir (default.<app>.yaml,.<app>.yml,.<app>.json;{app}is substituted;[]disables the local lookup) - the XDG default above
The work dir is --work-dir when WorkDirMixin is used, else the cwd.
On dispatch, cli_hook__config loads --conf-file (JSON always;
YAML with the config extra). Missing file yields {} unless
Meta.config_required is true. Loaded data is available as
ctx.config (dict) and cli_root.config (attribute namespace).
Source code in clak/comp/config.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |
cli_hook__config(instance, ctx, **_)
Load --conf-file once and expose it on ctx / root.
Source code in clak/comp/config.py
XDGDataDirMixin
XDGLogDirMixin
__getattr__(name)
Resolve __version__ and the optional clak.comp exports lazily.