Skip to content

clabe.apps

AsyncExecutor

Bases: Protocol

Protocol for asynchronous command execution.

Defines the interface for executing commands asynchronously using async/await patterns. Implementations should handle asynchronous process execution, output capture, and error handling.

Example
class CustomAsyncExecutor(AsyncExecutor):
    async def run_async(self, command: Command) -> CommandResult:
        # Custom async execution logic
        await asyncio.sleep(1)
        return CommandResult(stdout="output", stderr="", exit_code=0)

run_async async

run_async(command: Command) -> CommandResult

Execute the command asynchronously and return the result.

Source code in src/clabe/apps/_base.py
async def run_async(self, command: "Command") -> CommandResult:
    """Execute the command asynchronously and return the result."""
    ...

Command

Command(
    cmd: list[str],
    output_parser: _OutputParser[TOutput],
    inputs: dict[str, Path] | None = None,
)

Bases: Generic[TOutput]

Represents a command to be executed with customizable output parsing.

Encapsulates command execution logic, result management, and output parsing. Supports both synchronous and asynchronous execution patterns with type-safe output parsing.

Commands are provided as a list of strings, which is consistent with subprocess and executed directly without shell interpretation. This approach: - Avoids shell injection vulnerabilities - Handles arguments with spaces correctly without manual quoting - Is more portable across platforms

Attributes:

Name Type Description
cmd list[str]

The command to execute as a list of strings

result CommandResult

The result of command execution (available after execution)

Example
# Create a command
cmd = Command(cmd=["python", "-c", "print('hello')"], output_parser=identity_parser)

# Execute with a synchronous executor
executor = LocalExecutor()
result = cmd.execute(executor)

# Create a command with custom output parser
def parse_json(result: CommandResult) -> dict:
    return json.loads(result.stdout)

cmd = Command(cmd=["get-data", "--json"], output_parser=parse_json)
data = cmd.execute(executor)

Initialize the Command instance.

Parameters:

Name Type Description Default
cmd list[str]

The command to execute as a list of strings. The first element is the program to run, followed by its arguments.

required
output_parser _OutputParser[TOutput]

Function to parse the command result into desired output type

required
inputs dict[str, Path] | None

Local files the command reads, keyed by name, whose paths appear in cmd. Local executors ignore them; remote executors copy each file to the remote machine and point the command at the copy.

None
Example
cmd = Command(cmd=["echo", "hello"], output_parser=identity_parser)
Source code in src/clabe/apps/_base.py
def __init__(
    self, cmd: list[str], output_parser: _OutputParser[TOutput], inputs: dict[str, Path] | None = None
) -> None:
    """Initialize the Command instance.

    Args:
        cmd: The command to execute as a list of strings. The first element
            is the program to run, followed by its arguments.
        output_parser: Function to parse the command result into desired output type
        inputs: Local files the command reads, keyed by name, whose paths appear in ``cmd``.
            Local executors ignore them; remote executors copy each file to the remote
            machine and point the command at the copy.

    Example:
        ```python
        cmd = Command(cmd=["echo", "hello"], output_parser=identity_parser)
        ```
    """
    self._cmd: list[str] = cmd
    self._output_parser = output_parser
    self._result: CommandResult | None = None
    self._inputs: dict[str, Path] = dict(inputs or {})

inputs property

inputs: dict[str, Path]

Local files the command reads, keyed by name, whose paths appear in cmd.

result property

result: CommandResult

Get the command result.

cmd property

cmd: list[str]

Get the command as a list of strings.

append_arg

append_arg(args: str | list[str]) -> Self

Append arguments to the command.

Parameters:

Name Type Description Default
args str | list[str]

Argument(s) to append. Can be a single string or list of strings. Empty strings are filtered out.

required

Returns:

Type Description
Self

Self for method chaining.

Example
cmd = Command(cmd=["python"], output_parser=identity_parser)
cmd.append_arg(["-m", "pytest"])  # Results in ["python", "-m", "pytest"]
Source code in src/clabe/apps/_base.py
def append_arg(self, args: str | list[str]) -> Self:
    """Append arguments to the command.

    Args:
        args: Argument(s) to append. Can be a single string or list of strings.
            Empty strings are filtered out.

    Returns:
        Self for method chaining.

    Example:
        ```python
        cmd = Command(cmd=["python"], output_parser=identity_parser)
        cmd.append_arg(["-m", "pytest"])  # Results in ["python", "-m", "pytest"]
        ```
    """
    if isinstance(args, str):
        args = [args]
    args = [arg for arg in args if arg]
    self._cmd = self._cmd + args
    return self

execute

execute(executor: Executor) -> TOutput

Execute using a synchronous executor.

Source code in src/clabe/apps/_base.py
def execute(self, executor: Executor) -> TOutput:
    """Execute using a synchronous executor."""
    logger.info("Executing command: %s", self._cmd)
    with recorded(self, executor):
        started_at = _utc_now()
        self._set_result(_timed(executor.run(self), started_at))
    logger.info("Command execution completed.")
    return self._parse_output(self.result)

execute_async async

execute_async(executor: AsyncExecutor) -> TOutput

Execute using an async executor.

Source code in src/clabe/apps/_base.py
async def execute_async(self, executor: AsyncExecutor) -> TOutput:
    """Execute using an async executor."""
    logger.info("Executing command asynchronously: %s", self._cmd)
    with recorded(self, executor):
        started_at = _utc_now()
        self._set_result(_timed(await executor.run_async(self), started_at))
    logger.info("Command execution completed.")
    return self._parse_output(self.result)

CommandError

CommandError(
    exit_code: int,
    stdout: str | None = None,
    stderr: str | None = None,
)

Bases: Exception

Exception raised when a command execution fails.

This exception is raised by CommandResult.check_returncode() when a command exits with a non-zero exit code. It includes detailed information about the command execution failure.

Attributes:

Name Type Description
exit_code

The non-zero exit code returned by the command

stdout

Standard output from the command (may be None)

stderr

Standard error from the command (may be None)

message

Human-readable error message

Example
try:
    result = CommandResult(stdout="", stderr="File not found", exit_code=1)
    result.check_returncode()
except CommandError as e:
    print(f"Command failed with exit code {e.exit_code}")
    print(f"Error output: {e.stderr}")

Initialize the CommandError.

Parameters:

Name Type Description Default
exit_code int

The non-zero exit code from the command

required
stdout str | None

Standard output from the command

None
stderr str | None

Standard error from the command

None
Source code in src/clabe/apps/_base.py
def __init__(self, exit_code: int, stdout: str | None = None, stderr: str | None = None):
    """
    Initialize the CommandError.

    Args:
        exit_code: The non-zero exit code from the command
        stdout: Standard output from the command
        stderr: Standard error from the command
    """
    self.exit_code = exit_code
    self.stdout = stdout
    self.stderr = stderr

    # Build detailed error message
    message_parts = [f"Command failed with exit code {exit_code}"]

    if stderr:
        message_parts.append(f"stderr: {stderr}")
    if stdout:
        message_parts.append(f"stdout: {stdout}")

    self.message = "\n".join(message_parts)
    super().__init__(self.message)

CommandResult

Bases: BaseModel

Represents the result of a process execution.

started_at and ended_at are when the command was handed to its executor and when its result came back, as timezone-aware UTC times of the machine running the launcher (also for a command run on another machine). They are set by Command.execute / execute_async, and are None for a result built by hand.

ok property

ok: bool

Check if the command executed successfully by examining the exit code.

check_returncode

check_returncode() -> None

Raise CommandError if the exit code indicates failure.

Raises:

Type Description
CommandError

If exit_code is non-zero, includes exit_code, stdout, and stderr

Example
result = CommandResult(stdout="output", stderr="error", exit_code=1)
try:
    result.check_returncode()
except CommandError as e:
    print(f"Exit code: {e.exit_code}")
    print(f"Stderr: {e.stderr}")
Source code in src/clabe/apps/_base.py
def check_returncode(self) -> None:
    """
    Raise CommandError if the exit code indicates failure.

    Raises:
        CommandError: If exit_code is non-zero, includes exit_code, stdout, and stderr

    Example:
        ```python
        result = CommandResult(stdout="output", stderr="error", exit_code=1)
        try:
            result.check_returncode()
        except CommandError as e:
            print(f"Exit code: {e.exit_code}")
            print(f"Stderr: {e.stderr}")
        ```
    """
    if not self.ok:
        raise CommandError(exit_code=self.exit_code, stdout=self.stdout, stderr=self.stderr)

ExecutableApp

Bases: Protocol

Protocol defining the interface for executable applications.

Any class implementing this protocol must provide a command property that returns a Command object, enabling standardized execution across different application types.

Example
class MyApp(ExecutableApp):
    @property
    def command(self) -> Command:
        return Command(cmd=["echo", "hello"], output_parser=identity_parser)

command property

command: Command

Get the command to execute.

Executor

Bases: Protocol

Protocol for synchronous command execution.

Defines the interface for executing commands synchronously and obtaining results. Implementations should handle process execution, output capture, and error handling.

Example
class CustomExecutor(Executor):
    def run(self, command: Command) -> CommandResult:
        # Custom execution logic
        return CommandResult(stdout="output", stderr="", exit_code=0)

run

run(command: Command) -> CommandResult

Execute the command and return the result.

Source code in src/clabe/apps/_base.py
def run(self, command: "Command") -> CommandResult:
    """Execute the command and return the result."""
    ...

StdCommand

StdCommand(cmd: list[str])

Bases: Command[CommandResult]

Standard command that returns the raw CommandResult.

A convenience class that creates a Command with the identity_parser, returning the raw CommandResult without transformation.

Example
cmd = StdCommand(["echo", "hello"])
Source code in src/clabe/apps/_base.py
def __init__(self, cmd: list[str]) -> None:
    super().__init__(cmd, identity_parser)

inputs property

inputs: dict[str, Path]

Local files the command reads, keyed by name, whose paths appear in cmd.

result property

result: CommandResult

Get the command result.

cmd property

cmd: list[str]

Get the command as a list of strings.

append_arg

append_arg(args: str | list[str]) -> Self

Append arguments to the command.

Parameters:

Name Type Description Default
args str | list[str]

Argument(s) to append. Can be a single string or list of strings. Empty strings are filtered out.

required

Returns:

Type Description
Self

Self for method chaining.

Example
cmd = Command(cmd=["python"], output_parser=identity_parser)
cmd.append_arg(["-m", "pytest"])  # Results in ["python", "-m", "pytest"]
Source code in src/clabe/apps/_base.py
def append_arg(self, args: str | list[str]) -> Self:
    """Append arguments to the command.

    Args:
        args: Argument(s) to append. Can be a single string or list of strings.
            Empty strings are filtered out.

    Returns:
        Self for method chaining.

    Example:
        ```python
        cmd = Command(cmd=["python"], output_parser=identity_parser)
        cmd.append_arg(["-m", "pytest"])  # Results in ["python", "-m", "pytest"]
        ```
    """
    if isinstance(args, str):
        args = [args]
    args = [arg for arg in args if arg]
    self._cmd = self._cmd + args
    return self

execute

execute(executor: Executor) -> TOutput

Execute using a synchronous executor.

Source code in src/clabe/apps/_base.py
def execute(self, executor: Executor) -> TOutput:
    """Execute using a synchronous executor."""
    logger.info("Executing command: %s", self._cmd)
    with recorded(self, executor):
        started_at = _utc_now()
        self._set_result(_timed(executor.run(self), started_at))
    logger.info("Command execution completed.")
    return self._parse_output(self.result)

execute_async async

execute_async(executor: AsyncExecutor) -> TOutput

Execute using an async executor.

Source code in src/clabe/apps/_base.py
async def execute_async(self, executor: AsyncExecutor) -> TOutput:
    """Execute using an async executor."""
    logger.info("Executing command asynchronously: %s", self._cmd)
    with recorded(self, executor):
        started_at = _utc_now()
        self._set_result(_timed(await executor.run_async(self), started_at))
    logger.info("Command execution completed.")
    return self._parse_output(self.result)

AindBehaviorServicesBonsaiApp

AindBehaviorServicesBonsaiApp(
    workflow: PathLike,
    *,
    temp_directory: PathLike | None = None,
    rig: Rig | None = None,
    session: Session | None = None,
    task: Task | None = None,
    **kwargs,
)

Bases: BonsaiApp

Specialized Bonsai application for AIND behavior services integration.

This class extends the base BonsaiApp to provide specific functionality for AIND behavior experiments, including automatic configuration of task, session, and rig paths for the Bonsai workflow.

Example
# Create an AIND behavior services Bonsai app
app = AindBehaviorServicesBonsaiApp(workflow="behavior_workflow.bonsai")
app.run()

Initializes the AIND behavior services Bonsai app with automatic model configuration.

Automatically configures RigPath, SessionPath, and TaskPath properties for the Bonsai workflow by saving provided models to temporary files and passing their paths as externalized properties.

Attention: This class requires a local executor since it saves temporary files. Args: workflow: Path to the Bonsai workflow file launcher: The launcher instance for saving temporary models rig: Optional rig model to configure. Defaults to None session: Optional session model to configure. Defaults to None task: Optional task model to configure. Defaults to None **kwargs: Additional keyword arguments passed to BonsaiApp (executable, is_editor_mode, is_start_flag, additional_properties, cwd, timeout, additional_externalized_properties)

Example
from aind_behavior_services import (
    Rig,
    Session,
    Task
)

# Create models
rig = Rig(...)
session = Session(...)
task = Task(...)

# Create app with automatic configuration
app = AindBehaviorServicesBonsaiApp(
    workflow="behavior_workflow.bonsai",
    launcher=my_launcher,
    rig=rig,
    session=session,
    task=task
)
app.run()

# The workflow will receive:
# -p:"RigPath"="/tmp/rig_temp.json"
# -p:"SessionPath"="/tmp/session_temp.json"
# -p:"TaskPath"="/tmp/task_temp.json"
Source code in src/clabe/apps/_bonsai.py
def __init__(
    self,
    workflow: os.PathLike,
    *,
    temp_directory: os.PathLike | None = None,
    rig: Rig | None = None,
    session: Session | None = None,
    task: Task | None = None,
    **kwargs,
) -> None:
    """
    Initializes the AIND behavior services Bonsai app with automatic model configuration.

    Automatically configures RigPath, SessionPath, and TaskPath properties
    for the Bonsai workflow by saving provided models to temporary files and
    passing their paths as externalized properties.

    Attention: This class requires a local executor since it saves temporary files.
    Args:
        workflow: Path to the Bonsai workflow file
        launcher: The launcher instance for saving temporary models
        rig: Optional rig model to configure. Defaults to None
        session: Optional session model to configure. Defaults to None
        task: Optional task model to configure. Defaults to None
        **kwargs: Additional keyword arguments passed to BonsaiApp (executable,
            is_editor_mode, is_start_flag, additional_properties, cwd, timeout,
            additional_externalized_properties)

    Example:
        ```python
        from aind_behavior_services import (
            Rig,
            Session,
            Task
        )

        # Create models
        rig = Rig(...)
        session = Session(...)
        task = Task(...)

        # Create app with automatic configuration
        app = AindBehaviorServicesBonsaiApp(
            workflow="behavior_workflow.bonsai",
            launcher=my_launcher,
            rig=rig,
            session=session,
            task=task
        )
        app.run()

        # The workflow will receive:
        # -p:"RigPath"="/tmp/rig_temp.json"
        # -p:"SessionPath"="/tmp/session_temp.json"
        # -p:"TaskPath"="/tmp/task_temp.json"
        ```
    """
    self._temp_directory = Path(temp_directory or TMP_DIR)

    additional_externalized_properties = kwargs.pop("additional_externalized_properties", {}) or {}
    inputs = {
        name: Path(os.path.abspath(self._save_temp_model(model=model)))
        for name, model in (("RigPath", rig), ("SessionPath", session), ("TaskPath", task))
        if model
    }
    additional_externalized_properties.update({name: str(path) for name, path in inputs.items()})
    super().__init__(
        workflow=workflow, additional_externalized_properties=additional_externalized_properties, **kwargs
    )
    # Registered as inputs so a remote executor can stage them on the machine that runs the workflow
    self.command.inputs.update(inputs)

command property

Get the command to execute.

executable property

executable: Path

Returns the path to the Bonsai executable after validation.

run

run(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: Executor | None = None,
) -> CommandResult

Execute the command and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor Executor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
@runnable
def run(self, executor_kwargs: dict[str, Any] | None = None, *, executor: Executor | None = None) -> CommandResult:
    """Execute the command and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return self.command.execute(executor or LocalExecutor(**(executor_kwargs or {})))

run_async async

run_async(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: AsyncExecutor | None = None,
) -> CommandResult

Execute the command asynchronously and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor AsyncExecutor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
@runnable
async def run_async(
    self, executor_kwargs: dict[str, Any] | None = None, *, executor: AsyncExecutor | None = None
) -> CommandResult:
    """Execute the command asynchronously and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return await self.command.execute_async(executor or AsyncLocalExecutor(**(executor_kwargs or {})))

validate

validate() -> None

Validates the Bonsai application configuration.

Checks that the Bonsai executable and workflow file exist. Issues a warning if editor mode is enabled, as it may prevent proper completion detection.

Raises:

Type Description
FileNotFoundError

If the executable or workflow file is not found

Example
app = BonsaiApp(workflow="workflow.bonsai", executable="bonsai.exe")
app.validate()  # Called automatically during __init__
Source code in src/clabe/apps/_bonsai.py
def validate(self) -> None:
    """
    Validates the Bonsai application configuration.

    Checks that the Bonsai executable and workflow file exist. Issues a warning
    if editor mode is enabled, as it may prevent proper completion detection.

    Raises:
        FileNotFoundError: If the executable or workflow file is not found

    Example:
        ```python
        app = BonsaiApp(workflow="workflow.bonsai", executable="bonsai.exe")
        app.validate()  # Called automatically during __init__
        ```
    """
    if not self._executable:
        for potential_exe in ["./.bonsai/bonsai.exe", "./bonsai/bonsai.exe"]:
            if (loc := shutil.which(potential_exe)) is not None:
                self._executable = Path(loc)

    if (not self._executable) or (not Path(self.executable).exists()):
        raise FileNotFoundError(f"Executable not found: {self._executable}")
    if not Path(self.workflow).exists():
        raise FileNotFoundError(f"Workflow file not found: {self.workflow}")
    if self.is_editor_mode:
        logger.warning("Bonsai will run in editor mode. Will probably not be able to assert successful completion.")

BonsaiApp

BonsaiApp(
    workflow: PathLike,
    *,
    executable: PathLike | None = None,
    is_editor_mode: bool = True,
    is_start_flag: bool = True,
    additional_externalized_properties: dict[str, str]
    | None = None,
    skip_validation: bool = False,
)

Bases: ExecutableApp, _DefaultExecutorMixin

A class to manage the execution of Bonsai workflows.

Handles Bonsai workflow execution, configuration management, and process monitoring for behavioral experiments.

Methods:

Name Description
run

Executes the Bonsai workflow

get_result

Retrieves the result of the Bonsai execution

add_app_settings

Adds or updates application settings

validate

Validates the Bonsai application configuration

Initializes the BonsaiApp instance.

Parameters:

Name Type Description Default
workflow PathLike

Path to the Bonsai workflow file

required
executable PathLike | None

Path to the Bonsai executable. Defaults to None, which will trigger automatic discovery

None
is_editor_mode bool

Whether to run in editor mode. Defaults to True

True
is_start_flag bool

Whether to use the start flag. Defaults to True

True
additional_externalized_properties dict[str, str] | None

Additional externalized properties. Defaults to None

None
Example
# Create and run a Bonsai app
app = BonsaiApp(workflow="workflow.bonsai")
app.run()

# Create with custom settings
app = BonsaiApp(
    workflow="workflow.bonsai",
    is_editor_mode=False,
)
app.run()
Source code in src/clabe/apps/_bonsai.py
def __init__(
    self,
    workflow: os.PathLike,
    *,
    executable: os.PathLike | None = None,
    is_editor_mode: bool = True,
    is_start_flag: bool = True,
    additional_externalized_properties: dict[str, str] | None = None,
    skip_validation: bool = False,
) -> None:
    """
    Initializes the BonsaiApp instance.

    Args:
        workflow: Path to the Bonsai workflow file
        executable: Path to the Bonsai executable. Defaults to None, which will trigger automatic discovery
        is_editor_mode: Whether to run in editor mode. Defaults to True
        is_start_flag: Whether to use the start flag. Defaults to True
        additional_externalized_properties: Additional externalized properties. Defaults to None

    Example:
        ```python
        # Create and run a Bonsai app
        app = BonsaiApp(workflow="workflow.bonsai")
        app.run()

        # Create with custom settings
        app = BonsaiApp(
            workflow="workflow.bonsai",
            is_editor_mode=False,
        )
        app.run()
        ```
    """
    # Resolve paths
    self.workflow = Path(workflow).resolve()
    self._executable = executable
    self.is_editor_mode = is_editor_mode
    self.is_start_flag = is_start_flag if not is_editor_mode else True

    if not skip_validation:
        self.validate()

    __cmd = self._build_bonsai_process_command(
        workflow_file=self.workflow,
        bonsai_exe=self.executable,
        is_editor_mode=self.is_editor_mode,
        is_start_flag=self.is_start_flag,
        additional_properties=additional_externalized_properties or {},
    )
    self._command = Command[CommandResult](cmd=__cmd, output_parser=identity_parser)

executable property

executable: Path

Returns the path to the Bonsai executable after validation.

command property

Get the command to execute.

run

run(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: Executor | None = None,
) -> CommandResult

Execute the command and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor Executor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
@runnable
def run(self, executor_kwargs: dict[str, Any] | None = None, *, executor: Executor | None = None) -> CommandResult:
    """Execute the command and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return self.command.execute(executor or LocalExecutor(**(executor_kwargs or {})))

run_async async

run_async(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: AsyncExecutor | None = None,
) -> CommandResult

Execute the command asynchronously and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor AsyncExecutor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
@runnable
async def run_async(
    self, executor_kwargs: dict[str, Any] | None = None, *, executor: AsyncExecutor | None = None
) -> CommandResult:
    """Execute the command asynchronously and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return await self.command.execute_async(executor or AsyncLocalExecutor(**(executor_kwargs or {})))

validate

validate() -> None

Validates the Bonsai application configuration.

Checks that the Bonsai executable and workflow file exist. Issues a warning if editor mode is enabled, as it may prevent proper completion detection.

Raises:

Type Description
FileNotFoundError

If the executable or workflow file is not found

Example
app = BonsaiApp(workflow="workflow.bonsai", executable="bonsai.exe")
app.validate()  # Called automatically during __init__
Source code in src/clabe/apps/_bonsai.py
def validate(self) -> None:
    """
    Validates the Bonsai application configuration.

    Checks that the Bonsai executable and workflow file exist. Issues a warning
    if editor mode is enabled, as it may prevent proper completion detection.

    Raises:
        FileNotFoundError: If the executable or workflow file is not found

    Example:
        ```python
        app = BonsaiApp(workflow="workflow.bonsai", executable="bonsai.exe")
        app.validate()  # Called automatically during __init__
        ```
    """
    if not self._executable:
        for potential_exe in ["./.bonsai/bonsai.exe", "./bonsai/bonsai.exe"]:
            if (loc := shutil.which(potential_exe)) is not None:
                self._executable = Path(loc)

    if (not self._executable) or (not Path(self.executable).exists()):
        raise FileNotFoundError(f"Executable not found: {self._executable}")
    if not Path(self.workflow).exists():
        raise FileNotFoundError(f"Workflow file not found: {self.workflow}")
    if self.is_editor_mode:
        logger.warning("Bonsai will run in editor mode. Will probably not be able to assert successful completion.")

CurriculumApp

CurriculumApp(
    settings: CurriculumSettings,
    *,
    python_script_app_kwargs: dict[str, Any] | None = None,
)

Bases: ExecutableApp, _DefaultExecutorMixin

A curriculum application that manages the execution of behavior curriculum scripts.

Facilitates running curriculum modules within a managed Python environment, handling trainer state input/output and data directory management. The app processes session data through curriculum logic and generates suggestions for subsequent training stages.

Attributes:

Name Type Description
command Command

The underlying command that will be executed

Example
# Create and run curriculum app
settings = CurriculumSettings(
    input_trainer_state="/path/to/trainer_state.json",
    data_directory="/data/session_123"
)
app = CurriculumApp(settings)
app.run()
suggestion = app.process_suggestion()

# Access the updated trainer state
new_state = suggestion.trainer_state
metrics = suggestion.metrics

Initializes the CurriculumApp with the specified settings.

Configures the curriculum application by setting up the Python script runner with appropriate arguments for data directory, trainer state input, and optional curriculum selection.

Parameters:

Name Type Description Default
settings CurriculumSettings

Configuration settings for the curriculum application

required
python_script_app_kwargs dict[str, Any] | None

Optional keyword arguments to pass to PythonScriptApp

None

Raises:

Type Description
ValueError

If input_trainer_state or data_directory is not set in settings

Example
# Basic initialization
settings = CurriculumSettings(
    input_trainer_state="/path/to/state.json",
    data_directory="/data/session"
)
app = CurriculumApp(settings)

# With custom Python script app kwargs
app = CurriculumApp(
    settings,
    python_script_app_kwargs={"skip_validation": True}
)
Source code in src/clabe/apps/_curriculum.py
def __init__(
    self, settings: CurriculumSettings, *, python_script_app_kwargs: dict[str, t.Any] | None = None
) -> None:
    """
    Initializes the CurriculumApp with the specified settings.

    Configures the curriculum application by setting up the Python script runner
    with appropriate arguments for data directory, trainer state input, and
    optional curriculum selection.

    Args:
        settings: Configuration settings for the curriculum application
        python_script_app_kwargs: Optional keyword arguments to pass to PythonScriptApp

    Raises:
        ValueError: If input_trainer_state or data_directory is not set in settings

    Example:
        ```python
        # Basic initialization
        settings = CurriculumSettings(
            input_trainer_state="/path/to/state.json",
            data_directory="/data/session"
        )
        app = CurriculumApp(settings)

        # With custom Python script app kwargs
        app = CurriculumApp(
            settings,
            python_script_app_kwargs={"skip_validation": True}
        )
        ```
    """
    self._settings = settings

    if self._settings.input_trainer_state is None:
        raise ValueError("Input trainer state is not set.")
    if self._settings.data_directory is None:
        raise ValueError("Data directory is not set.")

    kwargs: dict[str, t.Any] = {  # Must use kebab casing
        "data-directory": str(self._settings.data_directory),
        "input-trainer-state": str(self._settings.input_trainer_state),
    }
    if self._settings.curriculum is not None:
        kwargs["curriculum"] = str(self._settings.curriculum)

    python_script_app_kwargs = python_script_app_kwargs or {}
    self._python_script_app = PythonScriptApp(
        script=settings.script,
        project_directory=settings.project_directory,
        extra_uv_arguments="-q",
        additional_arguments=[arg for kv in kwargs.items() for arg in ("--" + kv[0], str(kv[1]))],
        **python_script_app_kwargs,
    )

command property

command: Command

Get the command to execute.

run

run(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: Executor | None = None,
) -> CommandResult

Execute the command and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor Executor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
@runnable
def run(self, executor_kwargs: dict[str, Any] | None = None, *, executor: Executor | None = None) -> CommandResult:
    """Execute the command and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return self.command.execute(executor or LocalExecutor(**(executor_kwargs or {})))

run_async async

run_async(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: AsyncExecutor | None = None,
) -> CommandResult

Execute the command asynchronously and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor AsyncExecutor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
@runnable
async def run_async(
    self, executor_kwargs: dict[str, Any] | None = None, *, executor: AsyncExecutor | None = None
) -> CommandResult:
    """Execute the command asynchronously and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return await self.command.execute_async(executor or AsyncLocalExecutor(**(executor_kwargs or {})))

process_suggestion

process_suggestion() -> CurriculumSuggestion

Process and parse the curriculum command output into a CurriculumSuggestion.

Extracts the trainer state, metrics, and version information from the command execution stdout.

Returns:

Name Type Description
CurriculumSuggestion CurriculumSuggestion

Parsed curriculum suggestion with trainer state and metrics

Raises:

Type Description
ValueError

If no stdout is available from command execution or if parsing fails

Example
app = CurriculumApp(settings)
app.run()
suggestion = app.process_suggestion()
print(suggestion.trainer_state.stage.name)
Source code in src/clabe/apps/_curriculum.py
def process_suggestion(self) -> CurriculumSuggestion:
    """
    Process and parse the curriculum command output into a CurriculumSuggestion.

    Extracts the trainer state, metrics, and version information from the
    command execution stdout.

    Returns:
        CurriculumSuggestion: Parsed curriculum suggestion with trainer state and metrics

    Raises:
        ValueError: If no stdout is available from command execution or if parsing fails

    Example:
        ```python
        app = CurriculumApp(settings)
        app.run()
        suggestion = app.process_suggestion()
        print(suggestion.trainer_state.stage.name)
        ```
    """
    if self._python_script_app.command.result.stdout is None:
        raise ValueError("No stdout from curriculum command execution.")
    return CurriculumSuggestion.model_validate_json(self._python_script_app.command.result.stdout)

CurriculumOutcome

Bases: BaseModel

What steps.curriculum did: the suggestion, where it was saved, how it was run.

CurriculumSettings

Bases: ServiceSettings

Settings for the CurriculumApp.

Configuration for curriculum execution including script path, project directory, trainer state input, data handling, and curriculum selection.

Attributes:

Name Type Description
script list[str]

The curriculum script/command to execute. Defaults to "curriculum run"

project_directory PathLike

Root directory of the curriculum project. Defaults to current directory

input_trainer_state PathLike | None

Path to the input trainer state file

data_directory PathLike | None

Directory containing session data for curriculum processing

curriculum str | None

Optional specific curriculum name to use

Example
# Basic settings
settings = CurriculumSettings(
    input_trainer_state="/path/to/trainer_state.json",
    data_directory="/data/session"
)

# Settings with custom curriculum
settings = CurriculumSettings(
    script="curriculum run",
    project_directory="/path/to/curricula",
    input_trainer_state="/path/to/trainer_state.json",
    data_directory="/data/session",
    curriculum="advanced_training"
)

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

Customizes the settings sources to include the safe YAML settings source.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The settings class

required
init_settings PydanticBaseSettingsSource

The initial settings source

required
env_settings PydanticBaseSettingsSource

The environment settings source

required
dotenv_settings PydanticBaseSettingsSource

The dotenv settings source

required
file_secret_settings PydanticBaseSettingsSource

The file secret settings source

required

Returns:

Type Description
tuple[PydanticBaseSettingsSource, ...]

Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources

Source code in src/clabe/settings.py
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[ps.BaseSettings],
    init_settings: ps.PydanticBaseSettingsSource,
    env_settings: ps.PydanticBaseSettingsSource,
    dotenv_settings: ps.PydanticBaseSettingsSource,
    file_secret_settings: ps.PydanticBaseSettingsSource,
) -> tuple[ps.PydanticBaseSettingsSource, ...]:
    """
    Customizes the settings sources to include the safe YAML settings source.

    Args:
        settings_cls: The settings class
        init_settings: The initial settings source
        env_settings: The environment settings source
        dotenv_settings: The dotenv settings source
        file_secret_settings: The file secret settings source

    Returns:
        Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources
    """
    yaml_sources = [
        _SafeYamlSettingsSource(settings_cls, yaml_file=p, yaml_config_section=cls.__yml_section__)
        for p in KNOWN_CONFIG_FILES
    ]
    # The in-memory document (--clabe-yml) ranks above every file
    return (
        init_settings,
        _InMemorySettingsSource(settings_cls, config_section=cls.__yml_section__),
        *yaml_sources,
        env_settings,
        dotenv_settings,
        file_secret_settings,
    )

CurriculumSuggestion

Bases: BaseModel

Model representing a curriculum suggestion with trainer state and metrics.

This model encapsulates the output from a curriculum run, including the updated trainer state, performance metrics, and version information.

Attributes:

Name Type Description
trainer_state SerializeAsAny[TrainerState]

The updated trainer state after curriculum processing

metrics SerializeAsAny[Metrics]

Performance metrics from the curriculum run

version str

Version of the curriculum

dsl_version str

Version of the domain-specific language package used (aind-behavior-curriculum)

AsyncLocalExecutor

AsyncLocalExecutor(
    cwd: PathLike | None = None,
    env: dict[str, str] | None = None,
    timeout: float | None = None,
)

Bases: AsyncExecutor

Asynchronous executor for running commands on the local system.

Executes commands asynchronously using asyncio subprocess functions with configurable working directory and environment variables. Ideal for long-running processes or when multiple commands need to run concurrently.

Commands are executed directly without shell interpretation, which avoids shell injection vulnerabilities and handles arguments with spaces correctly.

Attributes:

Name Type Description
cwd

Working directory for command execution

env

Environment variables for the subprocess

timeout

Maximum execution time in seconds

Example
# Create async executor
executor = AsyncLocalExecutor()

# Execute a command asynchronously
cmd = Command(cmd=["echo", "hello"], output_parser=identity_parser)
result = await executor.run_async(cmd)

# Run multiple commands concurrently
executor = AsyncLocalExecutor(cwd="/workdir")
cmd1 = Command(cmd=["task1"], output_parser=identity_parser)
cmd2 = Command(cmd=["task2"], output_parser=identity_parser)
results = await asyncio.gather(
    executor.run_async(cmd1),
    executor.run_async(cmd2)
)

Initialize the asynchronous local executor.

Parameters:

Name Type Description Default
cwd PathLike | None

Working directory for command execution

None
env dict[str, str] | None

Environment variables for the subprocess

None
timeout float | None

Maximum execution time in seconds

None
Source code in src/clabe/apps/_executors.py
def __init__(
    self, cwd: os.PathLike | None = None, env: dict[str, str] | None = None, timeout: float | None = None
) -> None:
    """Initialize the asynchronous local executor.

    Args:
        cwd: Working directory for command execution
        env: Environment variables for the subprocess
        timeout: Maximum execution time in seconds

    """
    self.cwd = cwd or os.getcwd()
    self.env = env
    self.timeout = timeout
    #: Seconds a cancelled command's process gets to exit after being asked to, before it is killed.
    self.stop_timeout = 10.0

run_async async

run_async(command: Command) -> CommandResult

Execute the command asynchronously and return the result.

Parameters:

Name Type Description Default
command Command

The command to execute (as a list of strings)

required

Returns:

Type Description
CommandResult

CommandResult with stdout, stderr, and exit code

Raises:

Type Description
CommandError

If the command exits with non-zero exit code

TimeoutError

If the command exceeds the timeout

Example
executor = AsyncLocalExecutor()
cmd = Command(cmd=["echo", "hello"], output_parser=identity_parser)
result = await executor.run_async(cmd)
Source code in src/clabe/apps/_executors.py
async def run_async(self, command: Command) -> CommandResult:
    """Execute the command asynchronously and return the result.

    Args:
        command: The command to execute (as a list of strings)

    Returns:
        CommandResult with stdout, stderr, and exit code

    Raises:
        CommandError: If the command exits with non-zero exit code
        TimeoutError: If the command exceeds the timeout

    Example:
        ```python
        executor = AsyncLocalExecutor()
        cmd = Command(cmd=["echo", "hello"], output_parser=identity_parser)
        result = await executor.run_async(cmd)
        ```
    """
    proc = await asyncio.create_subprocess_exec(
        *command.cmd,
        cwd=self.cwd,
        env=self.env,
        stdin=asyncio.subprocess.DEVNULL,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )

    try:
        stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=self.timeout)
    except TimeoutError as exc:
        proc.kill()
        await proc.wait()
        assert self.timeout is not None
        raise subprocess.TimeoutExpired(" ".join(command.cmd), self.timeout) from exc
    except asyncio.CancelledError:
        # e.g. the run was aborted: stop the process rather than leave it running
        await _stop_process(proc, self.stop_timeout)
        raise

    if proc.returncode is None:
        raise RuntimeError("Process did not complete successfully and returned no return code.")

    command_result = CommandResult(
        stdout=stdout.decode(),
        stderr=stderr.decode(),
        exit_code=proc.returncode,
    )

    command_result.check_returncode()
    return command_result

LocalDetachedExecutor

LocalDetachedExecutor(
    cwd: PathLike | None = None,
    env: dict[str, str] | None = None,
)

Bases: Executor

Fire-and-forget executor that spawns a subprocess and returns immediately.

Launches the command via subprocess.Popen without waiting for it to finish. stdout and stderr are redirected to DEVNULL so that no pipe handles are left open. The returned CommandResult is a placeholder with exit_code=0 and no captured output; callers must not rely on it to reflect the actual process outcome.

Attributes:

Name Type Description
cwd

Working directory for command execution

env

Environment variables for the subprocess

Example
executor = LocalDetachedExecutor()
cmd = Command(cmd=["bonsai", "workflow.bonsai"], output_parser=identity_parser)
_ = executor.run(cmd)  # returns immediately; Bonsai keeps running

Initialize the detached executor.

Parameters:

Name Type Description Default
cwd PathLike | None

Working directory for command execution

None
env dict[str, str] | None

Environment variables for the subprocess

None
Source code in src/clabe/apps/_executors.py
def __init__(self, cwd: os.PathLike | None = None, env: dict[str, str] | None = None) -> None:
    """Initialize the detached executor.

    Args:
        cwd: Working directory for command execution
        env: Environment variables for the subprocess
    """
    self.cwd = cwd or os.getcwd()
    self.env = env

run

run(command: Command[Any]) -> CommandResult

Spawn the command and return immediately without waiting.

Parameters:

Name Type Description Default
command Command[Any]

The command to execute (as a list of strings)

required

Returns:

Type Description
CommandResult

A placeholder CommandResult with exit_code=0 and no output.

CommandResult

The actual process exit code is never captured.

Example
executor = LocalDetachedExecutor()
cmd = Command(cmd=["bonsai", "workflow.bonsai"], output_parser=identity_parser)
result = executor.run(cmd)  # fire-and-forget
Source code in src/clabe/apps/_executors.py
def run(self, command: Command[Any]) -> CommandResult:
    """Spawn the command and return immediately without waiting.

    Args:
        command: The command to execute (as a list of strings)

    Returns:
        A placeholder ``CommandResult`` with ``exit_code=0`` and no output.
        The actual process exit code is never captured.

    Example:
        ```python
        executor = LocalDetachedExecutor()
        cmd = Command(cmd=["bonsai", "workflow.bonsai"], output_parser=identity_parser)
        result = executor.run(cmd)  # fire-and-forget
        ```
    """
    subprocess.Popen(
        command.cmd,
        cwd=self.cwd,
        env=self.env,
        stdin=subprocess.DEVNULL,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        shell=False,
    )
    return CommandResult(stdout=None, stderr=None, exit_code=0)

LocalExecutor

LocalExecutor(
    cwd: PathLike | None = None,
    env: dict[str, str] | None = None,
    timeout: float | None = None,
)

Bases: Executor

Synchronous executor for running commands on the local system.

Executes commands using subprocess.run with configurable working directory and environment variables. Captures both stdout and stderr, and enforces return code checking.

Commands are executed directly without shell interpretation (shell=False), which avoids shell injection vulnerabilities and handles arguments with spaces correctly.

Attributes:

Name Type Description
cwd

Working directory for command execution

env

Environment variables for the subprocess

timeout

Maximum execution time in seconds

Example
# Create executor with default settings
executor = LocalExecutor()

# Create executor with custom working directory
executor = LocalExecutor(cwd="/path/to/workdir")

# Create executor with custom environment
executor = LocalExecutor(env={"KEY": "value"})

# Execute a command
cmd = Command(cmd=["echo", "hello"], output_parser=identity_parser)
result = executor.run(cmd)

Initialize the local executor.

Parameters:

Name Type Description Default
cwd PathLike | None

Working directory for command execution

None
env dict[str, str] | None

Environment variables for the subprocess

None
timeout float | None

Maximum execution time in seconds

None
Source code in src/clabe/apps/_executors.py
def __init__(
    self, cwd: os.PathLike | None = None, env: dict[str, str] | None = None, timeout: float | None = None
) -> None:
    """Initialize the local executor.

    Args:
        cwd: Working directory for command execution
        env: Environment variables for the subprocess
        timeout: Maximum execution time in seconds

    """
    self.cwd = cwd or os.getcwd()
    self.env = env
    self.timeout = timeout

run

run(command: Command[Any]) -> CommandResult

Execute the command and return the result.

Parameters:

Name Type Description Default
command Command[Any]

The command to execute (as a list of strings)

required

Returns:

Type Description
CommandResult

CommandResult with stdout, stderr, and exit code

Raises:

Type Description
CommandError

If the command exits with non-zero exit code

Example
executor = LocalExecutor()
cmd = Command(cmd=["echo", "hello"], output_parser=identity_parser)
result = executor.run(cmd)
Source code in src/clabe/apps/_executors.py
def run(self, command: Command[Any]) -> CommandResult:
    """Execute the command and return the result.

    Args:
        command: The command to execute (as a list of strings)

    Returns:
        CommandResult with stdout, stderr, and exit code

    Raises:
        CommandError: If the command exits with non-zero exit code

    Example:
        ```python
        executor = LocalExecutor()
        cmd = Command(cmd=["echo", "hello"], output_parser=identity_parser)
        result = executor.run(cmd)
        ```
    """
    proc = subprocess.run(
        command.cmd,
        cwd=self.cwd,
        env=self.env,
        text=True,
        stdin=subprocess.DEVNULL,  # apps read no input; an inherited console/pipe could block their start-up
        capture_output=True,
        check=False,
        timeout=self.timeout,
        shell=False,
    )
    result = CommandResult(stdout=proc.stdout, stderr=proc.stderr, exit_code=proc.returncode)
    result.check_returncode()
    return result

PythonScriptApp

PythonScriptApp(
    script: str | list[str],
    additional_arguments: list[str] | None = None,
    project_directory: PathLike = Path("."),
    extra_uv_arguments: str = "",
    optional_toml_dependencies: list[str] | None = None,
    append_python_exe: bool = False,
    skip_validation: bool = False,
)

Bases: ExecutableApp, _DefaultExecutorMixin

Application class for running Python scripts within a managed uv environment.

Facilitates running Python scripts with automatic virtual environment management, dependency handling, and script execution. Uses the uv tool for environment and dependency management, ensuring isolated and reproducible Python environments.

The app automatically validates uv installation, creates virtual environments if needed, and constructs proper uv run commands with all necessary flags and arguments.

Attributes:

Name Type Description
command Command[CommandResult]

The underlying command that will be executed

Example
# Simple script execution
app = PythonScriptApp(script="analyze_data.py")
result = app.run()

# With project dependencies
app = PythonScriptApp(
    script="process.py",
    project_directory="/path/to/project",
    optional_toml_dependencies=["data", "viz"]
)

# Module execution with arguments
app = PythonScriptApp(
    script="-m pytest",
    additional_arguments="tests/ -v --cov",
    extra_uv_arguments="-q"
)

# Async execution
result = await app.run_async()

Initializes the PythonScriptApp with the specified parameters.

Automatically validates the presence of uv and creates a virtual environment if one doesn't exist (unless skip_validation is True). Constructs the full uv run command with all specified arguments.

Parameters:

Name Type Description Default
script str | list[str]

The Python script command to be executed (e.g., "my_module.py" or "my_package run")

required
additional_arguments list[str] | None

Additional arguments to pass to the script. Defaults to None

None
project_directory PathLike

The directory where the project resides. Defaults to current directory

Path('.')
extra_uv_arguments str

Extra arguments to pass to the uv command (e.g., "-q" for quiet). Defaults to empty string

''
optional_toml_dependencies list[str] | None

Additional TOML dependency groups to include (e.g., ["dev", "test"]). Defaults to None

None
append_python_exe bool

Whether to append "python" before the script command. Defaults to False

False
skip_validation bool

Skip uv validation and environment checks. Defaults to False

False

Raises:

Type Description
RuntimeError

If uv is not installed (unless skip_validation=True)

Example
# Basic script execution
app = PythonScriptApp(script="test.py")
app.run()

# Script with module syntax
app = PythonScriptApp(script="-m pytest tests/")

# With dependencies and arguments
app = PythonScriptApp(
    script="my_module.py",
    additional_arguments="--verbose --output results.json",
    optional_toml_dependencies=["dev", "test"]
)

# With Python explicitly prepended
app = PythonScriptApp(
    script="script.py",
    append_python_exe=True,
    project_directory="/path/to/project"
)
Source code in src/clabe/apps/_python_script.py
def __init__(
    self,
    /,
    script: str | list[str],
    additional_arguments: list[str] | None = None,
    project_directory: os.PathLike = Path("."),
    extra_uv_arguments: str = "",
    optional_toml_dependencies: list[str] | None = None,
    append_python_exe: bool = False,
    skip_validation: bool = False,
) -> None:
    """
    Initializes the PythonScriptApp with the specified parameters.

    Automatically validates the presence of uv and creates a virtual environment
    if one doesn't exist (unless skip_validation is True). Constructs the full
    uv run command with all specified arguments.

    Args:
        script: The Python script command to be executed (e.g., "my_module.py" or "my_package run")
        additional_arguments: Additional arguments to pass to the script. Defaults to None
        project_directory: The directory where the project resides. Defaults to current directory
        extra_uv_arguments: Extra arguments to pass to the uv command (e.g., "-q" for quiet). Defaults to empty string
        optional_toml_dependencies: Additional TOML dependency groups to include (e.g., ["dev", "test"]). Defaults to None
        append_python_exe: Whether to append "python" before the script command. Defaults to False
        skip_validation: Skip uv validation and environment checks. Defaults to False

    Raises:
        RuntimeError: If uv is not installed (unless skip_validation=True)

    Example:
        ```python
        # Basic script execution
        app = PythonScriptApp(script="test.py")
        app.run()

        # Script with module syntax
        app = PythonScriptApp(script="-m pytest tests/")

        # With dependencies and arguments
        app = PythonScriptApp(
            script="my_module.py",
            additional_arguments="--verbose --output results.json",
            optional_toml_dependencies=["dev", "test"]
        )

        # With Python explicitly prepended
        app = PythonScriptApp(
            script="script.py",
            append_python_exe=True,
            project_directory="/path/to/project"
        )
        ```
    """
    script = [script] if isinstance(script, str) else script
    if not skip_validation:
        self._validate_uv()
        if not self._has_venv(project_directory):
            logger.warning("Python environment not found. Creating one...")
            self.create_environment(project_directory)

    cmd_args: list[str] = ["uv", "run"]
    if extra_uv_arguments:
        cmd_args.extend(extra_uv_arguments.split())
    cmd_args.extend(self._make_uv_optional_toml_dependencies(optional_toml_dependencies or []))
    cmd_args.extend(self._make_uv_project_directory(project_directory))
    if append_python_exe:
        cmd_args.append("python")
    cmd_args.extend(script)
    if additional_arguments:
        cmd_args.extend(additional_arguments)

    self._command = Command[CommandResult](cmd=cmd_args, output_parser=identity_parser)

command property

Get the command to execute.

run

run(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: Executor | None = None,
) -> CommandResult

Execute the command and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor Executor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
@runnable
def run(self, executor_kwargs: dict[str, Any] | None = None, *, executor: Executor | None = None) -> CommandResult:
    """Execute the command and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return self.command.execute(executor or LocalExecutor(**(executor_kwargs or {})))

run_async async

run_async(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: AsyncExecutor | None = None,
) -> CommandResult

Execute the command asynchronously and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor AsyncExecutor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
@runnable
async def run_async(
    self, executor_kwargs: dict[str, Any] | None = None, *, executor: AsyncExecutor | None = None
) -> CommandResult:
    """Execute the command asynchronously and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return await self.command.execute_async(executor or AsyncLocalExecutor(**(executor_kwargs or {})))

create_environment classmethod

create_environment(
    project_directory: PathLike,
    run_kwargs: dict[str, Any] | None = None,
) -> CompletedProcess

Creates a Python virtual environment using the uv tool.

Executes 'uv venv' to create a .venv directory in the specified project directory. This method is automatically called during initialization if no virtual environment is detected.

Parameters:

Name Type Description Default
project_directory PathLike

Directory where the virtual environment will be created

required
run_kwargs dict[str, Any] | None

Additional keyword arguments for subprocess.run. Defaults to None

None

Returns:

Type Description
CompletedProcess

subprocess.CompletedProcess: The result of the environment creation process

Raises:

Type Description
CalledProcessError

If the environment creation fails

Example
# Create a virtual environment
PythonScriptApp.create_environment("/path/to/project")

# Create with custom timeout
PythonScriptApp.create_environment(
    "/path/to/project",
    run_kwargs={"timeout": 60}
)
Source code in src/clabe/apps/_python_script.py
@classmethod
def create_environment(
    cls, project_directory: os.PathLike, run_kwargs: dict[str, Any] | None = None
) -> subprocess.CompletedProcess:
    """
    Creates a Python virtual environment using the uv tool.

    Executes 'uv venv' to create a .venv directory in the specified project
    directory. This method is automatically called during initialization if
    no virtual environment is detected.

    Args:
        project_directory: Directory where the virtual environment will be created
        run_kwargs: Additional keyword arguments for subprocess.run. Defaults to None

    Returns:
        subprocess.CompletedProcess: The result of the environment creation process

    Raises:
        subprocess.CalledProcessError: If the environment creation fails

    Example:
        ```python
        # Create a virtual environment
        PythonScriptApp.create_environment("/path/to/project")

        # Create with custom timeout
        PythonScriptApp.create_environment(
            "/path/to/project",
            run_kwargs={"timeout": 60}
        )
        ```
    """
    # TODO we should probably add a way to run this through our executors
    logger.info("Creating Python environment with uv venv at %s...", project_directory)
    run_kwargs = run_kwargs or {}
    cmd = ["uv", "venv"] + cls._make_uv_project_directory(project_directory)
    try:
        proc = subprocess.run(
            cmd,
            shell=False,
            capture_output=True,
            text=True,
            check=True,
            cwd=project_directory,
            **run_kwargs,
        )
    except subprocess.CalledProcessError as e:
        logger.error("Error creating Python environment. %s", e)
        raise
    return proc

identity_parser

identity_parser(result: CommandResult) -> CommandResult

Helper parser that returns the CommandResult as-is.

Source code in src/clabe/apps/_base.py
def identity_parser(result: CommandResult) -> CommandResult:
    """Helper parser that returns the CommandResult as-is."""
    return result