Pythonic task execution library for managing shell-oriented subprocesses and organizing executable Python code into CLI-invokable tasks
Overall
score
96%
Invoke provides a comprehensive argument parsing system that supports flags, options, positional arguments, help generation, and complex argument types with automatic CLI generation from task signatures.
Main CLI argument parser supporting contexts, flags, options, and positional arguments.
class Parser:
"""
Main CLI argument parser.
Handles parsing command-line arguments into structured contexts with
support for flags, options, positional arguments, and help generation.
Attributes:
- contexts (list): List of parsing contexts
- initial (ParserContext): Initial parsing context
- ignore_unknown (bool): Whether to ignore unknown arguments
"""
def __init__(self, contexts=None, initial=None, ignore_unknown=False):
"""
Initialize Parser.
Parameters:
- contexts (list, optional): Parsing contexts to use
- initial (ParserContext, optional): Initial context
- ignore_unknown (bool): Ignore unknown arguments instead of erroring
"""
def parse_argv(self, argv):
"""
Parse command-line arguments.
Parameters:
- argv (list): Command-line arguments to parse
Returns:
ParseResult: Parsed arguments organized by context
Raises:
ParseError: If argument parsing fails
"""
def print_help(self, name=None, text=None):
"""
Print help text for parser.
Parameters:
- name (str, optional): Program name
- text (str, optional): Additional help text
"""Command-line argument definition with validation and type conversion.
class Argument:
"""
Command-line argument definition.
Defines a single command-line argument including its names, type,
default value, help text, and parsing behavior.
Attributes:
- names (list): Argument names (including aliases)
- kind (type): Argument type (str, int, bool, etc.)
- default: Default value
- help (str): Help text
- positional (bool): Whether argument is positional
- optional (bool): Whether argument is optional
- incrementable (bool): Whether argument can be repeated to increment value
- iterable (bool): Whether argument accepts multiple values
- attr_name (str): Attribute name for storing parsed value
"""
def __init__(self, names=None, kind=str, default=None, help=None, positional=False, optional=None, incrementable=False, iterable=False, attr_name=None):
"""
Initialize Argument.
Parameters:
- names (list/str): Argument name(s)
- kind (type): Argument type for conversion
- default: Default value if not provided
- help (str): Help text description
- positional (bool): Whether this is a positional argument
- optional (bool): Whether argument is optional
- incrementable (bool): Can be repeated to increment (e.g., -vvv)
- iterable (bool): Accepts multiple values
- attr_name (str): Attribute name for parsed value storage
"""
@property
def name(self):
"""Primary argument name."""
@property
def nicknames(self):
"""Alternative argument names."""
@property
def takes_value(self):
"""Whether argument takes a value."""
def value_set(self, given):
"""
Set argument value with type conversion.
Parameters:
- given: Raw value to set
"""
@property
def value(self):
"""Current argument value."""
@property
def got_value(self):
"""Whether argument received a value."""Parser execution context containing parsed arguments for a specific command or task.
class ParserContext:
"""
Parser context containing arguments for a specific parsing scope.
Represents the parsed arguments for a single command, task, or parsing
context within a larger argument parsing operation.
Attributes:
- name (str): Context name
- aliases (list): Context aliases
- args (list): Parsed arguments
- positional_args (list): Positional arguments
- seen_flags (set): Flags that were encountered
"""
def __init__(self, name=None, aliases=None, args=None):
"""
Initialize ParserContext.
Parameters:
- name (str, optional): Context name
- aliases (list, optional): Context aliases
- args (list, optional): Arguments for this context
"""
def add_arg(self, *args, **kwargs):
"""
Add argument to this context.
Parameters:
- *args, **kwargs: Arguments passed to Argument constructor
Returns:
Argument: Added argument object
"""
def help_tuples(self):
"""
Generate help text tuples for arguments.
Returns:
list: List of (names, help_text) tuples
"""
def as_kwargs(self):
"""
Convert parsed arguments to keyword arguments dictionary.
Returns:
dict: Parsed arguments as keyword arguments
"""
def __getitem__(self, key):
"""Get argument value by name."""
def __contains__(self, key):
"""Test if argument exists."""
def __iter__(self):
"""Iterate over argument names."""Container for complete parsing results from multiple contexts.
class ParseResult(list):
"""
Parse result containing multiple parser contexts.
Behaves as a list of ParserContext objects representing the complete
parsing result from command-line arguments.
"""
def __getitem__(self, index):
"""Get context by index or name."""
def __iter__(self):
"""Iterate over contexts."""
def remainder(self):
"""Get unparsed remainder arguments."""High-level CLI program management integrating parsing with task execution.
class Program:
"""
Top-level CLI program management.
Coordinates argument parsing, task loading, help generation, and
task execution for complete CLI application functionality.
Attributes:
- name (str): Program name
- namespace (Collection): Task namespace
- config_class (type): Configuration class to use
- executor_class (type): Executor class to use
- loader_class (type): Collection loader class
- parser_class (type): Parser class to use
- config (Config): Program configuration
- initial_context (Context): Initial execution context
"""
def __init__(self, name=None, namespace=None, version=None, config_class=None, executor_class=None, loader_class=None, parser_class=None):
"""
Initialize Program.
Parameters:
- name (str, optional): Program name
- namespace (Collection, optional): Task collection
- version (str, optional): Program version
- config_class (type, optional): Config class
- executor_class (type, optional): Executor class
- loader_class (type, optional): Loader class
- parser_class (type, optional): Parser class
"""
def run(self, argv=None, exit=None):
"""
Run the program with given arguments.
Parameters:
- argv (list, optional): Command-line arguments
- exit (bool, optional): Whether to exit on completion
Returns:
any: Program result
"""
def parse_core(self, argv):
"""
Parse core program arguments.
Parameters:
- argv (list): Command-line arguments
Returns:
tuple: (core_args, task_args)
"""
def parse_tasks(self, args):
"""
Parse task-specific arguments.
Parameters:
- args (list): Task arguments to parse
Returns:
ParseResult: Parsed task arguments
"""
def execute(self, *args, **kwargs):
"""
Execute parsed tasks.
Parameters:
- *args, **kwargs: Execution arguments
"""
def print_help(self):
"""Print program help text."""
def print_version(self):
"""Print program version."""
def list_tasks(self, format='nested'):
"""
List available tasks.
Parameters:
- format (str): Output format ('nested', 'flat', 'json')
"""from invoke.parser import Parser, Argument, ParserContext
# Create argument definitions
ctx = ParserContext(name='mytask')
ctx.add_arg('--verbose', '-v', kind=bool, help='Verbose output')
ctx.add_arg('--count', '-c', kind=int, default=1, help='Repeat count')
ctx.add_arg('filename', positional=True, help='File to process')
# Create parser
parser = Parser([ctx])
# Parse arguments
result = parser.parse_argv(['mytask', '--verbose', '--count', '3', 'data.txt'])
# Access parsed values
task_ctx = result[0]
print(task_ctx.as_kwargs()) # {'verbose': True, 'count': 3, 'filename': 'data.txt'}from invoke import task
@task(help={'name': 'Name to greet', 'loud': 'Use uppercase'})
def hello(ctx, name='World', loud=False):
"""Say hello to someone."""
greeting = f"Hello {name}!"
if loud:
greeting = greeting.upper()
print(greeting)
# CLI usage:
# invoke hello --name John --loud
# invoke hello -n John -lfrom invoke import task
@task(
iterable=['exclude'], # Can specify multiple --exclude args
incrementable=['verbose'] # Can use -v, -vv, -vvv for levels
)
def process(ctx, file='data.txt', exclude=None, verbose=0, dry_run=False):
"""Process file with options."""
excludes = exclude or []
if verbose >= 1:
print(f"Processing {file}")
if verbose >= 2:
print(f"Excluding: {excludes}")
if verbose >= 3:
print("Debug mode enabled")
if dry_run:
print("Dry run - no changes made")
else:
# Do actual processing
pass
# CLI usage:
# invoke process --file data.csv --exclude logs --exclude temp -vvv --dry-runfrom invoke.parser import Parser, Argument, ParserContext
# Create contexts for different commands
deploy_ctx = ParserContext('deploy')
deploy_ctx.add_arg('--env', default='staging', help='Target environment')
deploy_ctx.add_arg('--force', kind=bool, help='Force deployment')
test_ctx = ParserContext('test')
test_ctx.add_arg('--coverage', kind=bool, help='Generate coverage report')
test_ctx.add_arg('--pattern', help='Test pattern to run')
# Create parser with multiple contexts
parser = Parser([deploy_ctx, test_ctx])
# Parse different command sets
deploy_result = parser.parse_argv(['deploy', '--env', 'production', '--force'])
test_result = parser.parse_argv(['test', '--coverage', '--pattern', 'test_*.py'])from invoke import Program, Collection, task
@task
def hello(ctx, name='World'):
"""Say hello."""
print(f"Hello {name}!")
@task
def goodbye(ctx, name='World'):
"""Say goodbye."""
print(f"Goodbye {name}!")
# Create task collection
ns = Collection(hello, goodbye)
# Create program
program = Program(name='greetings', namespace=ns, version='1.0.0')
# Run program (this handles all argument parsing)
if __name__ == '__main__':
program.run()
# CLI usage:
# python greetings.py hello --name John
# python greetings.py goodbye --name Jane
# python greetings.py --help
# python greetings.py --versionfrom invoke import task
@task(help={
'env': 'Target environment (staging, production)',
'force': 'Skip confirmation prompts',
'rollback': 'Rollback to previous version if deployment fails'
})
def deploy(ctx, env='staging', force=False, rollback=True):
"""
Deploy application to specified environment.
This command handles the complete deployment process including:
- Building the application
- Running tests
- Deploying to target environment
- Running health checks
"""
# Implementation here
pass
# CLI help output:
# invoke deploy --help
#
# Usage: invoke [--core-opts] deploy [--options] [other tasks here ...]
#
# Docstring:
# Deploy application to specified environment.
#
# This command handles the complete deployment process including:
# - Building the application
# - Running tests
# - Deploying to target environment
# - Running health checks
#
# Options:
# -e STRING, --env=STRING Target environment (staging, production)
# -f, --force Skip confirmation prompts
# -r, --rollback Rollback to previous version if deployment failsfrom invoke.parser import Parser, ParserContext
from invoke.exceptions import ParseError
try:
ctx = ParserContext('task')
ctx.add_arg('--count', kind=int, help='Number of items')
parser = Parser([ctx])
result = parser.parse_argv(['task', '--count', 'not-a-number'])
except ParseError as e:
print(f"Argument parsing failed: {e}")
# Handle parsing error gracefullyInstall with Tessl CLI
npx tessl i tessl/pypi-invokedocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10