Skip to content

cli

cli

Interactive commissioning and motion tooling for gantry position recording.

MotionSession is available without any extras — it has no dependency on prompt_toolkit or rich.

The interactive REPL (applied_motion.cli.cli) and the cli optional-dependency extra require the cli extra::

1
pip install festo-dev-applied-motion[cli]

Typical usage::

1
2
3
4
5
6
from applied_motion.cli import MotionSession

session = MotionSession(gantry, on_capture=my_hook)
session.jog("X", "+", 5.0)
session.capture("deck_a1")
session.save("deck_layout.json")

To launch the interactive REPL::

1
applied-motion --config gantry.json

MotionSession

MotionSession(
    gantry: Gantry, on_capture: OnCaptureHook | None = None
)

Records gantry positions interactively or programmatically.

Provides step-jog and position capture on top of a connected Gantry. Captured positions are kept in positions and can be persisted to and from JSON via save / load.

This class has no knowledge of the gantry backend (Modbus vs FPosBAPI) and no dependency on prompt_toolkit or rich. Backend-specific post-capture actions (e.g. sending TEACH_POS to the PLC) are performed by the caller through the on_capture hook.

Parameters:

Name Type Description Default
gantry Gantry

Connected and homed Gantry instance.

required
on_capture OnCaptureHook | None

Optional hook called immediately after each successful capture. Receives the position label and position dict. Exceptions raised by the hook propagate to the caller.

None

Attributes:

Name Type Description
positions dict[str, dict[str, float]]

Ordered dict mapping label → {axis_name: position_mm}. Populated by capture and load.

Example::

1
2
3
4
5
6
7
8
9
# FPosBAPI: wire a hook that commits positions to the PLC
def plc_hook(label, pos):
    gantry.teach_pos(pos_id=label_to_id[label])


session = MotionSession(gantry, on_capture=plc_hook)
session.jog("X", "+", 5.0)
session.capture("deck_a1")
session.save("deck_layout.json")
Source code in src/applied_motion/cli/session.py
def __init__(  # noqa
    self,
    gantry: Gantry,
    on_capture: OnCaptureHook | None = None,
) -> None:
    self.gantry = gantry
    self.on_capture = on_capture
    self.positions: dict[str, dict[str, float]] = {}
    logger.debug(
        "MotionSession: created for gantry=%r hook=%s",
        gantry,
        getattr(on_capture, "__name__", repr(on_capture)) if on_capture is not None else "None",
    )

jog

jog(
    axis_name: str,
    direction: str,
    step_mm: float,
    velocity: float = 10.0,
    timeout: int = 15,
) -> dict[str, float]

Step-move one axis by step_mm in direction.

Reads the current axis position, computes an absolute target, and dispatches a single-axis move via Gantry.move_to.

Parameters:

Name Type Description Default
axis_name str

Name of the axis to jog (must be a key in axes).

required
direction str

"+" to move in the positive direction, "-" to move in the negative direction.

required
step_mm float

Distance to step in millimetres. Must be positive.

required
velocity float

Jog speed in mm/s. Defaults to 10.0.

10.0
timeout int

Maximum seconds to wait for the move to complete. When exceeded the axis backend issues a stop command and the move is abandoned. Defaults to 30 seconds — long enough for any normal jog step, but ensures the axis will always halt rather than run indefinitely.

15

Returns:

Type Description
dict[str, float]

Full gantry location dict after the move completes.

Raises:

Type Description
ValueError

If direction is not "+" or "-", or if step_mm is not positive.

KeyError

If axis_name is not registered with the gantry.

Source code in src/applied_motion/cli/session.py
def jog(
    self,
    axis_name: str,
    direction: str,
    step_mm: float,
    velocity: float = 10.0,
    timeout: int = 15,
) -> dict[str, float]:
    """Step-move one axis by *step_mm* in *direction*.

    Reads the current axis position, computes an absolute target, and
    dispatches a single-axis move via
    [`Gantry.move_to`][applied_motion.applied_motion.Gantry.move_to].

    Args:
        axis_name: Name of the axis to jog (must be a key in
            ``axes``).
        direction: ``"+"`` to move in the positive direction, ``"-"``
            to move in the negative direction.
        step_mm: Distance to step in millimetres.  Must be positive.
        velocity: Jog speed in mm/s.  Defaults to ``10.0``.
        timeout: Maximum seconds to wait for the move to complete.
            When exceeded the axis backend issues a stop command and
            the move is abandoned.  Defaults to ``30`` seconds —
            long enough for any normal jog step, but ensures the
            axis will always halt rather than run indefinitely.

    Returns:
        Full gantry location dict after the move completes.

    Raises:
        ValueError: If *direction* is not ``"+"`` or ``"-"``, or if
            *step_mm* is not positive.
        KeyError: If *axis_name* is not registered with the gantry.
    """
    if direction not in ("+", "-"):
        raise ValueError(f"direction must be '+' or '-', got {direction!r}")
    if step_mm <= 0:
        raise ValueError(f"step_mm must be positive, got {step_mm!r}")
    if axis_name not in self.gantry.axes:
        raise KeyError(f"Axis {axis_name!r} is not registered with this gantry")

    axis = self.gantry.axes[axis_name]
    current = axis.get_current_axis_position()
    raw_delta = step_mm if direction == "+" else -step_mm
    if raw_delta > 0:
        available = max(0.0, axis.max_position - current - _JOG_LIMIT_MARGIN)
        delta = min(raw_delta, available)
    else:
        available = max(0.0, current - axis.min_position - _JOG_LIMIT_MARGIN)
        delta = max(raw_delta, -available)

    logger.info(
        "MotionSession.jog: axis=%s limits=[%.3f, %.3f] mm current=%.3f delta=%.3f vel=%.1f mm/s timeout=%ss",
        axis_name,
        axis.min_position,
        axis.max_position,
        current,
        delta,
        velocity,
        timeout,
    )
    if delta != raw_delta:
        logger.warning(
            "MotionSession.jog: axis=%s delta clamped %.3f\u2192%.3f mm (%s mm margin from SW limit)",
            axis_name,
            raw_delta,
            delta,
            _JOG_LIMIT_MARGIN,
        )
    if abs(delta) < 1e-3:
        logger.info("MotionSession.jog: axis=%s at limit, skipping move", axis_name)
        return self.gantry.get_location()

    axis.move(delta, velocity, position_type="relative", timeout=timeout)
    location = self.gantry.get_location()
    logger.debug("MotionSession.jog: post-move location=%s", location)
    return location

capture

capture(label: str) -> dict[str, float]

Record the current gantry position under label.

Calls Gantry.get_location, stores the result in positions, then invokes on_capture if one was provided.

Parameters:

Name Type Description Default
label str

Unique name for this position (e.g. "deck_a1"). Overwrites any previous entry with the same label.

required

Returns:

Type Description
dict[str, float]

The recorded position dict {axis_name: position_mm}.

Source code in src/applied_motion/cli/session.py
def capture(self, label: str) -> dict[str, float]:
    """Record the current gantry position under *label*.

    Calls [`Gantry.get_location`][applied_motion.applied_motion.Gantry.get_location], stores
    the result in ``positions``, then invokes *on_capture* if one
    was provided.

    Args:
        label: Unique name for this position (e.g. ``"deck_a1"``).
            Overwrites any previous entry with the same label.

    Returns:
        The recorded position dict ``{axis_name: position_mm}``.

    Raises:
        Any exception raised by *on_capture* propagates unchanged.
    """
    position = self.gantry.get_location()
    self.positions[label] = position
    logger.info("MotionSession.capture: label=%r position=%s", label, position)
    if self.on_capture is not None:
        self.on_capture(label, position)
    return position

save

save(path: Path | str) -> None

Write all captured positions to a JSON file.

The output format is a plain JSON object mapping label → {axis_name: position_mm}.

Parameters:

Name Type Description Default
path Path | str

Destination file path. Parent directories must exist.

required
Source code in src/applied_motion/cli/session.py
def save(self, path: Path | str) -> None:
    """Write all captured positions to a JSON file.

    The output format is a plain JSON object mapping label →
    ``{axis_name: position_mm}``.

    Args:
        path: Destination file path.  Parent directories must exist.
    """
    path = Path(path)
    with path.open("w") as fh:
        json.dump(self.positions, fh, indent=2)
    logger.info("MotionSession.save: wrote %d position(s) to %s", len(self.positions), path)

load

load(path: Path | str) -> None

Merge positions from a JSON file into positions.

Existing labels are overwritten by entries from path; labels absent in path are preserved.

Parameters:

Name Type Description Default
path Path | str

Source JSON file previously written by save.

required

Raises:

Type Description
OSError

If path cannot be opened.

ValueError

If the file contains invalid JSON.

Source code in src/applied_motion/cli/session.py
def load(self, path: Path | str) -> None:
    """Merge positions from a JSON file into ``positions``.

    Existing labels are overwritten by entries from *path*; labels
    absent in *path* are preserved.

    Args:
        path: Source JSON file previously written by [`save`][applied_motion.cli.session.MotionSession.save].

    Raises:
        OSError: If *path* cannot be opened.
        ValueError: If the file contains invalid JSON.
    """
    path = Path(path)
    with path.open() as fh:
        loaded: dict[str, dict[str, float]] = json.load(fh)
    self.positions.update(loaded)
    logger.info("MotionSession.load: read %d position(s) from %s", len(loaded), path)

Command dataclass

Command(
    name: str,
    handler: CommandHandler,
    usage: str = "",
    help: str = "",
    completions: Callable[[], list[str]] | None = None,
)

A single named leaf command in a command group.

CommandGroup

CommandGroup(name: str, help: str = '')

A composable namespace of commands and nested child groups.

Initialise an empty command group.

Parameters:

Name Type Description Default
name str

The group's own name.

required
help str

Short description of the group.

''
Source code in src/applied_motion/cli/compose/core.py
def __init__(self, name: str, help: str = "") -> None:
    """Initialise an empty command group.

    Args:
        name: The group's own name.
        help: Short description of the group.
    """
    self.name = name
    self.help = help
    self.commands: dict[str, Command] = {}
    self.children: dict[str, CommandGroup] = {}
    logger.debug("CommandGroup created: name=%s", name)

add_command

add_command(command: Command) -> Command

Register a leaf command on this group.

Parameters:

Name Type Description Default
command Command

The command to register.

required

Returns:

Type Description
Command

The registered command.

Source code in src/applied_motion/cli/compose/core.py
def add_command(self, command: Command) -> Command:
    """Register a leaf command on this group.

    Args:
        command: The command to register.

    Returns:
        The registered command.
    """
    self.commands[command.name.lower()] = command
    return command

add_child

add_child(
    group: CommandGroup, name: str | None = None
) -> CommandGroup

Mount a child group under a name.

Parameters:

Name Type Description Default
group CommandGroup

The child group to mount.

required
name str | None

Mount key. Defaults to the child group's name.

None

Returns:

Type Description
CommandGroup

The mounted child group.

Source code in src/applied_motion/cli/compose/core.py
def add_child(self, group: "CommandGroup", name: str | None = None) -> "CommandGroup":
    """Mount a child group under a name.

    Args:
        group: The child group to mount.
        name: Mount key. Defaults to the child group's name.

    Returns:
        The mounted child group.
    """
    key = (name or group.name).lower()
    self.children[key] = group
    logger.debug("CommandGroup %s mounted child under %r", self.name, key)
    return group

dispatch

dispatch(tokens: Sequence[str]) -> None

Route a token sequence to a child group or a local command.

Parameters:

Name Type Description Default
tokens Sequence[str]

The whitespace-split command line.

required

Raises:

Type Description
UnknownCommandError

If no matching child or command is found.

Source code in src/applied_motion/cli/compose/core.py
def dispatch(self, tokens: Sequence[str]) -> None:
    """Route a token sequence to a child group or a local command.

    Args:
        tokens: The whitespace-split command line.

    Raises:
        UnknownCommandError: If no matching child or command is found.
    """
    if not tokens:
        return
    head = tokens[0].lower()
    rest = tokens[1:]
    if head in self.children:
        self.children[head].dispatch(rest)
        return
    if head in self.commands:
        self.commands[head].handler(rest)
        return
    raise UnknownCommandError(f"Unknown command: {tokens[0]!r}")

iter_paths

iter_paths(
    prefix: Sequence[str] = (),
) -> Iterator[tuple[str, ...]]

Yield the fully-qualified path of every command in the tree.

Parameters:

Name Type Description Default
prefix Sequence[str]

Internal prefix accumulator.

()

Yields:

Type Description
tuple[str, ...]

Tuples of namespace names ending in a command name.

Source code in src/applied_motion/cli/compose/core.py
def iter_paths(self, prefix: Sequence[str] = ()) -> Iterator[tuple[str, ...]]:
    """Yield the fully-qualified path of every command in the tree.

    Args:
        prefix: Internal prefix accumulator.

    Yields:
        Tuples of namespace names ending in a command name.
    """
    for name in self.commands:
        yield (*tuple(prefix), name)
    for child_name, child in self.children.items():
        yield from child.iter_paths((*tuple(prefix), child_name))

format_help

format_help(indent: int = 0) -> list[str]

Build indented help lines for this group and all descendants.

Parameters:

Name Type Description Default
indent int

Current indentation depth.

0

Returns:

Type Description
list[str]

A list of formatted help lines.

Source code in src/applied_motion/cli/compose/core.py
def format_help(self, indent: int = 0) -> list[str]:
    """Build indented help lines for this group and all descendants.

    Args:
        indent: Current indentation depth.

    Returns:
        A list of formatted help lines.
    """
    pad = "  " * indent
    lines: list[str] = []
    for cmd in self.commands.values():
        usage = cmd.usage or cmd.name
        suffix = f"    {cmd.help}" if cmd.help else ""
        lines.append(f"{pad}{usage}{suffix}")
    for child_name, child in self.children.items():
        header = f"{pad}{child_name}"
        if child.help:
            header = f"{header}    {child.help}"
        lines.append(header)
        lines.extend(child.format_help(indent + 1))
    return lines

UnknownCommandError

Bases: CommandError

Raise when a token matches neither a child group nor a local command.

UsageError

Bases: CommandError

Raise when a command is invoked with missing or invalid arguments.

build_standalone_motion_parser

build_standalone_motion_parser(
    *,
    prog: str = "applied-motion",
    extensions: Sequence[MotionCliExtension] = (),
) -> argparse.ArgumentParser

Build standalone motion CLI parser.

Parameters:

Name Type Description Default
prog str

Program name shown in help output.

'applied-motion'
extensions Sequence[MotionCliExtension]

Optional extension hooks for additional subcommands.

()

Returns:

Type Description
ArgumentParser

Fully configured standalone parser.

Source code in src/applied_motion/cli/cli.py
def build_standalone_motion_parser(
    *,
    prog: str = "applied-motion",
    extensions: Sequence[MotionCliExtension] = (),
) -> argparse.ArgumentParser:
    """Build standalone motion CLI parser.

    Args:
        prog: Program name shown in help output.
        extensions: Optional extension hooks for additional subcommands.

    Returns:
        Fully configured standalone parser.
    """
    parser = argparse.ArgumentParser(
        prog=prog,
        description="Composable motion control CLI for teach-in and axis operations.",
    )
    parser.add_argument(
        "--config",
        required=True,
        type=Path,
        metavar="PATH",
        help="Path to gantry JSON configuration file.",
    )
    parser.add_argument(
        "--gantry-name",
        default="gantry_1",
        metavar="NAME",
        help="Gantry component name in config (default: gantry_1).",
    )
    parser.add_argument(
        "--log-level",
        default="OFF",
        choices=LOG_LEVEL_CHOICES,
        metavar="LEVEL",
        help="Python logging level (default: OFF).",
    )
    subparsers = parser.add_subparsers(dest="motion_command")
    _add_motion_command_parsers(subparsers)
    for extension in extensions:
        extension(subparsers)
    return parser

dispatch_motion_command

dispatch_motion_command(args: Namespace) -> int

Dispatch parsed motion command namespace.

Initialises the gantry once and passes it to the selected handler. Guarantees gantry.close() is called on exit regardless of outcome.

Parameters:

Name Type Description Default
args Namespace

Parsed argument namespace from a motion parser.

required

Returns:

Type Description
int

Process exit code.

Raises:

Type Description
ValueError

If no command handler is available in args.

Source code in src/applied_motion/cli/cli.py
def dispatch_motion_command(args: argparse.Namespace) -> int:
    """Dispatch parsed motion command namespace.

    Initialises the gantry once and passes it to the selected handler.
    Guarantees ``gantry.close()`` is called on exit regardless of outcome.

    Args:
        args: Parsed argument namespace from a motion parser.

    Returns:
        Process exit code.

    Raises:
        ValueError: If no command handler is available in *args*.
    """
    if hasattr(args, "log_level"):
        configure_logging(args.log_level)

    handler = getattr(args, "_handler", None)
    if handler is None:
        raise ValueError("No motion command selected")
    gantry = _connect_gantry(args.config, args.gantry_name)
    try:
        return handler(args, gantry)
    finally:
        gantry.close()

register_motion_cli

register_motion_cli(
    parent_subparsers: _SubParsersAction,
    *,
    command_name: str = "motion",
    extensions: Sequence[MotionCliExtension] = (),
) -> argparse.ArgumentParser

Attach motion CLI subtree to parent parser.

Designed for higher-level system CLIs that compose multiple domains (for example motion and fluid) side-by-side.

Parameters:

Name Type Description Default
parent_subparsers _SubParsersAction

Parent parser subcommand registry.

required
command_name str

Name used for mounted motion command subtree.

'motion'
extensions Sequence[MotionCliExtension]

Optional extension hooks that can add extra motion subcommands.

()

Returns:

Type Description
ArgumentParser

Mounted motion command parser.

Source code in src/applied_motion/cli/cli.py
def register_motion_cli(
    parent_subparsers: argparse._SubParsersAction,
    *,
    command_name: str = "motion",
    extensions: Sequence[MotionCliExtension] = (),
) -> argparse.ArgumentParser:
    """Attach motion CLI subtree to parent parser.

    Designed for higher-level system CLIs that compose multiple domains
    (for example ``motion`` and ``fluid``) side-by-side.

    Args:
        parent_subparsers: Parent parser subcommand registry.
        command_name: Name used for mounted motion command subtree.
        extensions: Optional extension hooks that can add extra motion
            subcommands.

    Returns:
        Mounted motion command parser.
    """
    parser = parent_subparsers.add_parser(command_name, help="Motion control commands")
    parser.add_argument(
        "--config",
        required=True,
        type=Path,
        metavar="PATH",
        help="Path to gantry JSON configuration file.",
    )
    parser.add_argument(
        "--gantry-name",
        default="gantry_1",
        metavar="NAME",
        help="Gantry component name in config (default: gantry_1).",
    )
    parser.add_argument(
        "--log-level",
        default="INHERIT",
        choices=INHERITED_LOG_LEVEL_CHOICES,
        metavar="LEVEL",
        help="Python logging level (default: INHERIT from parent CLI, else OFF).",
    )
    motion_subparsers = parser.add_subparsers(dest="motion_command")
    _add_motion_command_parsers(motion_subparsers)
    for extension in extensions:
        extension(motion_subparsers)
    return parser

run_repl

run_repl(session: MotionSession, gantry: Gantry) -> int

Launch the interactive teach-in REPL for a connected gantry.

Presents a prompt-toolkit REPL that accepts jog, capture, where, home, teach pos, teach tray, list, save, load, help, and quit commands. Tab-completion and command history are provided automatically.

Parameters:

Name Type Description Default
session MotionSession

A MotionSession instance backed by a connected, homed gantry. Captured positions accumulate in session.positions.

required
gantry Gantry

The connected Gantry instance whose axes define the tab-completion candidates and receive motion commands.

required
Source code in src/applied_motion/cli/cli.py
def run_repl(session: MotionSession, gantry: Gantry) -> int:  # noqa
    """Launch the interactive teach-in REPL for a connected gantry.

    Presents a prompt-toolkit REPL that accepts ``jog``, ``capture``,
    ``where``, ``home``, ``teach pos``, ``teach tray``, ``list``, ``save``,
    ``load``, ``help``, and ``quit`` commands.  Tab-completion and command
    history are provided automatically.

    Args:
        session: A [`MotionSession`][applied_motion.cli.session.MotionSession]
            instance backed by a connected, homed gantry.  Captured
            positions accumulate in ``session.positions``.
        gantry: The connected [`Gantry`][applied_motion.applied_motion.Gantry]
            instance whose axes define the tab-completion candidates and
            receive motion commands.
    """
    axis_names = list(gantry.axes.keys())
    ps: PromptSession[str] = PromptSession(
        history=InMemoryHistory(),
        completer=_build_completer(axis_names),
    )

    console.print(_HELP_TEXT)

    previous_disable = logging.root.manager.disable
    logging.disable(logging.CRITICAL)
    try:
        while True:
            try:
                raw = ps.prompt("motion> ").strip()
            except (EOFError, KeyboardInterrupt):  # noqa
                console.print("\n[festo.muted]Exiting.[/]")
                return 130

            if not raw:
                continue

            parts = raw.split()
            cmd = parts[0].lower()

            try:
                if cmd in ("quit", "exit", "q"):
                    console.print("[festo.ok]✓[/] Quitting program.")
                    break

                elif cmd == "help":
                    console.print(_HELP_TEXT)

                elif cmd == "where":
                    loc = gantry.get_location()
                    console.print(_location_table(loc))

                elif cmd == "home":
                    gantry.home()
                    console.print("[festo.ok]✓[/] All axes homed.")

                elif cmd == "jog":
                    if len(parts) == 1:
                        # No args → enter arrow-key jog TUI
                        _run_jog_mode(session, gantry)
                    elif len(parts) < 4:
                        console.print(f"{format_badge('USAGE', 'warn')} [festo.brand]jog[/]")
                        console.print(f"    {format_help_line('jog', 'Enter arrow-key jog mode')}")
                        console.print(
                            f"    {format_help_line('jog <axis> <+/-> <step> [vel]', 'Single step-move (mm, default vel=10 mm/s)')}"
                        )
                    else:
                        axis = parts[1].upper()
                        direction = parts[2]
                        step = float(parts[3])
                        vel = float(parts[4]) if len(parts) > 4 else 10.0
                        try:
                            loc = session.jog(axis, direction, step, vel)
                            console.print(_location_table(loc))
                        except (ValueError, KeyError) as exc:
                            console.print(f"[festo.err]✗[/] {exc}")
                        except Exception as exc:
                            logger.exception(
                                "CLI command 'jog': failed axis=%s direction=%s step=%s vel=%s",
                                axis,
                                direction,
                                step,
                                vel,
                            )
                            console.print(f"[festo.err]✗[/] Move rejected by axis: {exc}")

                elif cmd == "capture":
                    if len(parts) < 2:
                        console.print(f"[festo.err]✗[/] Usage: {format_help_line('capture <label>')}")
                        continue
                    label = parts[1]
                    session.capture(label)
                    console.print(f"[festo.ok]✓[/] Captured [bold]{label!r}[/]")

                elif cmd == "teach":
                    if not gantry.supports_teach():
                        console.print(
                            f"{format_badge('TEACH DISABLED', 'warn')} [festo.muted]Modbus backend has no PLC teach command.[/]\n"
                            "    Use [festo.ok]capture[/] to save positions to JSON instead."
                        )
                    elif len(parts) >= 3 and parts[1] == "pos":
                        pos_id = int(parts[2])
                        gantry.teach_pos(pos_id=pos_id)
                        console.print(f"[festo.ok]✓[/] TEACH_POS sent ([festo.ok]pos_id={pos_id}[/])")
                    elif len(parts) >= 4 and parts[1] == "tray":
                        tray_id, tray_pos = int(parts[2]), int(parts[3])
                        gantry.teach_tray(tray_id=tray_id, tray_pos=tray_pos)
                        console.print(
                            f"[festo.ok]✓[/] TEACH_TRAY sent ([festo.ok]tray_id={tray_id}[/], [festo.ok]tray_pos={tray_pos}[/])"
                        )
                    else:
                        console.print("[festo.err]✗[/] Usage:")
                        console.print(f"    {format_help_line('teach pos <pos_id>')}")
                        console.print(f"    {format_help_line('teach tray <tray_id> <tray_pos>')}")

                elif cmd == "list":
                    if not session.positions:
                        console.print("[festo.muted]No positions captured yet.[/]")
                    else:
                        console.print(_positions_table(session.positions))

                elif cmd == "save":
                    if len(parts) < 2:
                        console.print(f"[festo.err]✗[/] Usage: {format_help_line('save <path>')}")
                        continue
                    session.save(parts[1])
                    console.print(f"[festo.ok]✓[/] {len(session.positions)} position(s) saved → [bold]{parts[1]}[/]")

                elif cmd == "load":
                    if len(parts) < 2:
                        console.print(f"[festo.err]✗[/] Usage: {format_help_line('load <path>')}")
                        continue
                    before = len(session.positions)
                    session.load(parts[1])
                    added = len(session.positions) - before
                    console.print(f"[festo.ok]✓[/] {added} position(s) loaded from [bold]{parts[1]}[/]")

                elif cmd == "loglevel":
                    console.print(f"[festo.ok]✓[/] {set_runtime_log_level(parts[1:])}")

                else:
                    console.print(f"[festo.err]✗[/] Unknown command: [bold]{cmd!r}[/]  (type [festo.ok]help[/])")

            except (KeyError, ValueError, IndexError) as exc:
                console.print(f"[festo.err]✗[/] {exc}")
            except Exception as exc:
                logger.exception("Unexpected error processing command %r", raw)
                console.print(f"[festo.err]✗[/] Unexpected error: {exc}")
    finally:
        logging.disable(previous_disable)

    console.print("[festo.ok]✓[/] Quitting program repl successful.")
    return 1