A batteries included task runner that works well with poetry and uv
—
Core classes and functions for embedding poethepoet functionality into other applications. Provides full control over task execution, configuration management, and environment setup.
The PoeThePoet class serves as the primary interface for programmatic usage, handling task resolution, execution, and configuration management.
class PoeThePoet:
def __init__(
self,
cwd: Path | str | None = None,
config: Mapping[str, Any] | PoeConfig | None = None,
output: PoeIO | IO = None,
poetry_env_path: str | None = None,
config_name: str | None = None,
program_name: str = "poe",
env: Mapping[str, str] | None = None,
suppress_args: Sequence[str] = tuple()
):
"""
Initialize PoeThePoet application.
Args:
cwd: Working directory path
config: Configuration object or mapping
output: Output handler for messages
poetry_env_path: Poetry virtual environment path
config_name: Configuration file name
program_name: Program name for help text
env: Environment variables
suppress_args: Arguments to suppress in help
"""
def __call__(self, cli_args: Sequence[str], internal: bool = False) -> int:
"""
Execute with CLI arguments.
Args:
cli_args: Command line arguments
internal: Internal execution flag
Returns:
Exit code (0 for success)
"""
def resolve_task(self, allow_hidden: bool = False) -> PoeTask | None:
"""
Resolve task by name from configuration.
Args:
allow_hidden: Allow hidden tasks (starting with _)
Returns:
Resolved task object or None if not found
"""
def run_task(self, task: PoeTask, context: RunContext | None = None) -> int | None:
"""
Execute a specific task.
Args:
task: Task object to execute
context: Execution context
Returns:
Exit code or None
"""
def get_run_context(self, multistage: bool = False) -> RunContext:
"""
Get execution context for task running.
Args:
multistage: Enable multistage context
Returns:
Runtime context object
"""
def modify_verbosity(self, offset: int) -> None:
"""
Adjust verbosity level.
Args:
offset: Verbosity change (-2 to +2)
"""
def print_help(
self,
info: str | None = None,
error: str | PoeException | None = None
) -> None:
"""
Print help message.
Args:
info: Additional info message
error: Error message or exception
"""The PoeConfig class handles loading and parsing of task configurations from various file formats.
class PoeConfig:
def __init__(
self,
cwd: Optional[Union[Path, str]] = None,
table: Optional[Mapping[str, Any]] = None,
config_name: Optional[Union[str, Sequence[str]]] = None,
io: Optional["PoeIO"] = None
):
"""
Initialize configuration manager.
Args:
cwd: Working directory
table: Pre-loaded configuration table
config_name: Config file name(s) to search for
io: IO handler for messages
"""
def load(
self,
target_path: Optional[Union[Path, str]] = None,
strict: bool = True
) -> None:
"""
Load configuration from files.
Args:
target_path: Specific path to load from
strict: Strict validation mode
"""
def lookup_task(self, name: str) -> Mapping[str, Any]:
"""
Look up task definition by name.
Args:
name: Task name to look up
Returns:
Task definition mapping
"""
def partitions(self, included_first=True) -> Iterator[ConfigPartition]:
"""
Get configuration partitions.
Args:
included_first: Include first partition
Yields:
Configuration partition objects
"""
def resolve_git_path(self, resource_path: str) -> str:
"""
Resolve git-relative paths.
Args:
resource_path: Resource path to resolve
Returns:
Resolved absolute path
"""
# Properties
@property
def executor(self) -> Mapping[str, Any]:
"""Executor configuration."""
@property
def task_names(self) -> Iterator[str]:
"""Available task names."""
@property
def tasks(self) -> dict[str, Any]:
"""Task definitions mapping."""
@property
def default_task_type(self) -> str:
"""Default task type."""
@property
def shell_interpreter(self) -> tuple[str, ...]:
"""Shell interpreter command."""
@property
def verbosity(self) -> int:
"""Verbosity level."""
@property
def is_poetry_project(self) -> bool:
"""Whether project uses Poetry."""
@property
def is_uv_project(self) -> bool:
"""Whether project uses UV."""
@property
def project_dir(self) -> Path:
"""Project root directory."""The PoeIO class manages input/output streams and verbosity control for poethepoet operations.
class PoeIO:
def __init__(
self,
parent: PoeIO | None = None,
output: IO | None = None,
error: IO | None = None,
input: IO | None = None,
baseline_verbosity: int | None = None,
verbosity_offset: int | None = None,
ansi: bool | None = None,
make_default: bool = False
):
"""
Initialize IO handler.
Args:
parent: Parent IO handler
output: Output stream
error: Error stream
input: Input stream
baseline_verbosity: Base verbosity level
verbosity_offset: Verbosity offset
ansi: ANSI color support
make_default: Make default IO instance
"""
@classmethod
def get_default_io(cls) -> "PoeIO":
"""Get default IO instance."""
def configure(self, ansi_enabled, baseline, offset, dont_override) -> None:
"""Configure IO settings."""
def print(
self,
message,
message_verbosity=0,
end="\n"
) -> None:
"""
Print message with verbosity control.
Args:
message: Message to print
message_verbosity: Required verbosity level
end: Line ending character
"""
def print_warning(
self,
message,
message_verbosity=0,
prefix="Warning",
end="\n"
) -> None:
"""Print warning message."""
def print_error(self, message, message_verbosity=0, end="\n") -> None:
"""Print error message."""
def print_debug(self, message, message_verbosity=0, end="\n") -> None:
"""Print debug message."""
def is_debug_enabled(self) -> bool:
"""Check if debug mode is enabled."""The PoeUi class handles command-line interface construction and argument parsing.
class PoeUi:
def __init__(
self,
io: PoeIO,
program_name: str = "poe",
suppress_args: Sequence[str] = tuple()
):
"""
Initialize UI manager.
Args:
io: IO handler
program_name: Program name for help
suppress_args: Arguments to suppress
"""
def build_parser(self) -> ArgumentParser:
"""Build argument parser."""
def parse_args(self, cli_args: Sequence[str]) -> Tuple[...]:
"""Parse CLI arguments."""
def print_help(self, tasks, info=None, error=None) -> None:
"""Print help message."""
def print_error(self, error) -> None:
"""Print error message."""
def print_version(self) -> None:
"""Print version information."""Context objects manage task execution state and environment.
class RunContext:
"""Runtime execution context for task execution."""
class InitializationContext:
"""Task initialization context."""
class TaskOutputCache:
"""Task output caching."""
class ContextProtocol:
"""Context interface protocol."""The Virtualenv class provides virtual environment detection and executable resolution.
class Virtualenv:
def __init__(self, path: Union[Path, str]):
"""
Initialize virtualenv handler.
Args:
path: Path to virtual environment
"""
def exists(self) -> bool:
"""Check if virtualenv exists."""
def bin_dir(self) -> Path:
"""Get binary directory path."""
def resolve_executable(self, executable: str) -> str:
"""
Resolve executable in virtualenv.
Args:
executable: Executable name to resolve
Returns:
Full path to executable
"""
@classmethod
def detect(cls, parent_dir: Path) -> bool:
"""
Detect virtualenv in directory.
Args:
parent_dir: Directory to search in
Returns:
True if virtualenv detected
"""from poethepoet.app import PoeThePoet
from poethepoet.io import PoeIO
from pathlib import Path
import sys
# Create IO handler
io = PoeIO(output=sys.stdout, error=sys.stderr)
# Create application with custom configuration
app = PoeThePoet(
cwd=Path("."),
output=io,
program_name="my_task_runner"
)
# Execute task
result = app(cli_args=["test", "--verbose"])from poethepoet.config import PoeConfig
from pathlib import Path
# Load configuration from specific file
config = PoeConfig(cwd=Path("."))
config.load("./custom_tasks.toml")
# Access task definitions
for task_name in config.task_names:
task_def = config.lookup_task(task_name)
print(f"Task {task_name}: {task_def}")from poethepoet.app import PoeThePoet
from pathlib import Path
app = PoeThePoet(cwd=Path("."))
# Resolve specific task
task = app.resolve_task("test")
if task:
# Get execution context
context = app.get_run_context()
# Run the task
result = app.run_task(task, context)
print(f"Task completed with exit code: {result}")Install with Tessl CLI
npx tessl i tessl/pypi-poethepoet