overall changes
This commit is contained in:
@@ -1,15 +1,43 @@
|
||||
# scott
|
||||
# Scott
|
||||
|
||||
A framework to create scoped task-oriented terminal tools.
|
||||
_A small Python framework for building scoped, task-oriented terminal tools._
|
||||
|
||||
## Run these
|
||||
Scott provides the shared command-line plumbing for applications made up of focused commands. Each
|
||||
command can live in its own module, define its own arguments, and be loaded only when the
|
||||
application registers it. The application keeps ownership of its business logic; Scott handles the
|
||||
common CLI mechanics.
|
||||
|
||||
```sh
|
||||
pip install --upgrade build
|
||||
```
|
||||
## What Scott provides
|
||||
|
||||
You can then run
|
||||
- A thin layer over Python's standard-library `argparse` module
|
||||
- Dynamically loaded commands
|
||||
- Command-specific arguments and help text
|
||||
- A small handler contract that keeps commands self-contained
|
||||
- Centralized command registration and dispatch
|
||||
|
||||
```sh
|
||||
python -m build
|
||||
```
|
||||
Scott is designed for small to medium-sized Python tools that need several related commands without
|
||||
introducing a larger CLI framework.
|
||||
|
||||
## How it fits together
|
||||
|
||||
At a high level, a Scott application has an entry point that registers command names. Scott resolves
|
||||
each name to a command handler, lets that handler extend its subparser, and dispatches the parsed
|
||||
arguments to the selected command. The complete application layout and handler contract are
|
||||
documented in [The Anatomy of a Scott application](docs/anatomy.md).
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Install Scott](docs/install.md) — install from a built wheel, Git repository, or local checkout
|
||||
- [The Anatomy of a Scott application](docs/anatomy.md) — application structure and command handlers
|
||||
- [Scott API Reference](docs/api-reference.md) — constructors, registration, dispatch, and behavior
|
||||
- [Build from Source](docs/build-from-source.md) — create distributable package artifacts
|
||||
|
||||
## Development
|
||||
|
||||
The project uses a standard Python package layout and `pyproject.toml` build configuration.
|
||||
For development installation and packaging instructions, see
|
||||
[Build from Source](docs/build-from-source.md).
|
||||
|
||||
## License
|
||||
|
||||
Scott is distributed under the [DuxTechnica Limited Use Source Code License Agreement](LICENSE).
|
||||
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
---
|
||||
title: The Anatomy of a Scott application
|
||||
---
|
||||
|
||||
## Anatomy of a Scott application
|
||||
|
||||
A Scott application is a plain Python script (the *entry point*) plus a `commands/` directory of
|
||||
command packages, laid out like this:
|
||||
|
||||
```
|
||||
scott-app/
|
||||
├── main.py # entry point script
|
||||
└── commands/
|
||||
├── cmd1/
|
||||
│ └── handler.py # implements the `cmd1` command
|
||||
├── cmd2/
|
||||
│ └── handler.py # implements the `cmd2` command
|
||||
└── cmd3/
|
||||
└── handler.py # implements the `cmd3` command
|
||||
```
|
||||
|
||||
Each command name maps to `commands/<name>/handler.py`. The entry point registers the
|
||||
commands it wants to expose, and Scott imports and dispatches them dynamically.
|
||||
|
||||
### The entry point
|
||||
|
||||
For the above example this would be the `main.py` script. Typically, this would look like:
|
||||
|
||||
```python
|
||||
from scott import Scott
|
||||
|
||||
def main():
|
||||
# app_dir: path of this script — Scott resolves it to locate the tools/ directory
|
||||
# app_desc: description shown in the tool's help output
|
||||
scott = Scott(__file__, "A toolset to do something")
|
||||
|
||||
commands = [
|
||||
"cmd1",
|
||||
"cmd2",
|
||||
"cmd3",
|
||||
]
|
||||
for cmd in commands:
|
||||
scott.register(cmd)
|
||||
scott.run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
Running the tool:
|
||||
|
||||
```sh
|
||||
$ python main.py --help
|
||||
usage: main.py [-h] {cmd1,cmd2,cmd3} ...
|
||||
|
||||
A toolset to do something
|
||||
|
||||
positional arguments:
|
||||
{cmd1,cmd2,cmd3}
|
||||
cmd1 description for cmd1
|
||||
cmd2 description for cmd2
|
||||
cmd3 description for cmd3
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
```
|
||||
|
||||
## The command contract
|
||||
|
||||
Every command module (`commands/<name>/handler.py`) is a plain Python module. Scott recognizes the
|
||||
following functions within `handler.py`:
|
||||
|
||||
| Function | Required | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `s_run(args)` | **Yes** | The command's entry point. Called with the parsed `argparse` namespace. |
|
||||
| `s_description()` | Optional | Returns a short help string shown in the command list. |
|
||||
| `s_arguments(parser)` | Optional | Registers command-specific options on the command's subparser. |
|
||||
|
||||
__`s_run(args)` — required__
|
||||
|
||||
The command's main function. It **must accept exactly one argument** (the parsed `argparse`
|
||||
namespace); registration is skipped with a warning otherwise.
|
||||
|
||||
```python
|
||||
def s_run(args):
|
||||
# args contains any options registered via scott_arguments(),
|
||||
# plus args.command (the subcommand name)
|
||||
print("command: cmd1")
|
||||
```
|
||||
|
||||
__`s_description()` — optional__
|
||||
|
||||
Returns a one-line description used as the command's help text in the parent help listing.
|
||||
|
||||
```python
|
||||
def s_description():
|
||||
return "description for cmd1"
|
||||
```
|
||||
|
||||
__`s_arguments(parser)` — optional__
|
||||
|
||||
Receives the command's `argparse` subparser so the command can define its own positional arguments
|
||||
and options. They arrive in `args` at dispatch time.
|
||||
|
||||
```python
|
||||
def s_arguments(parser):
|
||||
parser.add_argument(
|
||||
"posarg",
|
||||
help="The positional argument."
|
||||
)
|
||||
```
|
||||
|
||||
A complete command module:
|
||||
|
||||
```python
|
||||
# commands/cmd1/handler.py
|
||||
|
||||
def s_description():
|
||||
return "description for cmd1"
|
||||
|
||||
def s_arguments(parser):
|
||||
parser.add_argument(
|
||||
"posarg",
|
||||
help="The positional argument."
|
||||
)
|
||||
|
||||
def s_run(args):
|
||||
print(f"command: cmd1, posarg: {args.posarg}")
|
||||
```
|
||||
|
||||
Which produces:
|
||||
|
||||
```sh
|
||||
$ python main.py cmd1 --help
|
||||
usage: main.py cmd1 [-h] posarg
|
||||
|
||||
positional arguments:
|
||||
posarg The positional argument.
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: Scott API Reference
|
||||
---
|
||||
|
||||
# Scott API Reference
|
||||
|
||||
__`Scott(app_dir: str, app_desc: str = "")`__
|
||||
|
||||
Creates the framework and its argument parser.
|
||||
|
||||
- `app_dir` — typically `__file__` from the entry script. Scott resolves it to the containing
|
||||
directory, which is used to (a) locate the `commands/` packages and (b) is prepended to `sys.path`
|
||||
so the tool works no matter which directory you invoke it from.
|
||||
|
||||
- `app_desc` — description shown at the top of the tool's help output.
|
||||
|
||||
__`Scott.register(cmd_name: str)`__
|
||||
|
||||
Registers a command by dynamically importing `commands.<cmd_name>.handler`. During registration Scott:
|
||||
|
||||
1. Imports the command module; if it cannot be imported, prints a warning to *stderr* and skips
|
||||
the command.
|
||||
|
||||
2. Verifies `s_run` method exists, is callable, and takes **exactly one** parameter; otherwise warns
|
||||
to *stderr* and skips the command.
|
||||
|
||||
3. Creates an `argparse` subparser named `cmd_name`, using `s_description()` (if present) as its
|
||||
help text.
|
||||
|
||||
1. Calls `handler.s_arguments(subparser)` (if present) so the command can add options.
|
||||
|
||||
Skipped commands never appear in help output and cannot be invoked.
|
||||
|
||||
__`Scott.run()`__
|
||||
|
||||
Parses the process arguments and dispatches to the selected command's `s_run(args)`.
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
title: Scott - Build From Source
|
||||
---
|
||||
|
||||
# Scott - Build From Source
|
||||
|
||||
Open a terminal and change the active directory to the project root folder for `Scott`.
|
||||
|
||||
Follow the given steps in order to create a clean Python sandbox, activate it, install the build
|
||||
tool, and then use that tool to compile `Scott` into distributable artifacts.
|
||||
|
||||
__Step 1: Create an isolated virtual environment.__
|
||||
|
||||
```sh
|
||||
python -m venv .venv
|
||||
```
|
||||
|
||||
The virtual environment is created in a folder called `.venv` under the project root folder. This
|
||||
gives the project its own Python interpreter and package space, so dependencies don't conflict with
|
||||
the system Python or other projects.
|
||||
|
||||
__Step 2: Activate the virtual environment.__
|
||||
|
||||
```sh
|
||||
source .venv/bin/activate
|
||||
```
|
||||
|
||||
Activation happens for the current shell session only. It prepends `.venv/bin/` to your `PATH`, so
|
||||
`python` and `pip` now resolve to the environment's copies. Your prompt typically changes to show
|
||||
`(.venv)`.
|
||||
|
||||
__Step 3: Install (or upgrade) the build package.__
|
||||
|
||||
```sh
|
||||
pip install --upgrade build
|
||||
```
|
||||
|
||||
The virtual environment now has the latest `build` package. `build` is the PyPA-recommended PEP 517
|
||||
build frontend — it reads the project's `pyproject.toml`, sets up an isolated build environment, and
|
||||
invokes the configured build backend (`setuptools`) to produce distribution artifacts.
|
||||
|
||||
__Step 4: Build Scott as a package__
|
||||
|
||||
```sh
|
||||
python -m build
|
||||
```
|
||||
|
||||
By default the build process produces both a **source distribution** (`.tar.gz` sdist) and a
|
||||
**wheel** (`.whl`) in the `dist/` directory under the project root folder.
|
||||
|
||||
The resulting files in `dist/` are what you'd upload to PyPI or install with `pip install`.
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
---
|
||||
title: Scott - Install
|
||||
---
|
||||
|
||||
# Installing Scott
|
||||
|
||||
You can install Scott for your application using one of the following mechanisms:
|
||||
|
||||
## Option 1: Install from a built wheel
|
||||
|
||||
Follow the instructions to [build Scott from source](build-from-source.md). Then from the
|
||||
`{project-root}/dist` folder, install the wheel with pip:
|
||||
|
||||
```sh
|
||||
cd /your/application/project/root
|
||||
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
|
||||
pip install {project-root}/dist/*.whl
|
||||
```
|
||||
|
||||
This assumes that your application is using a virtual environment.
|
||||
|
||||
## Option 2: Install from a Git repository
|
||||
|
||||
This is the recommended approach. `Scott` is hosted as a Python package on a Git repository at
|
||||
|
||||
https://rprime.indroneel.co/termhole/scott.git
|
||||
|
||||
You can install directly from this repository instead of a built wheel. Use pip with the repository URL.
|
||||
|
||||
```sh
|
||||
cd /your/application/project/root
|
||||
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
|
||||
pip install "git+https://rprime.indroneel.co/termhole/scott.git"
|
||||
```
|
||||
|
||||
__Using the Python build tool__
|
||||
|
||||
If your application is managed with Python build tooling, you can declare `Scott` as a dependency in your app's `pyproject.toml` instead of installing it manually with `pip`.
|
||||
|
||||
Add the following entry under the project's dependencies:
|
||||
|
||||
```toml
|
||||
dependencies = [
|
||||
"scott @ git+https://rprime.indroneel.co/termhole/scott.git"
|
||||
]
|
||||
```
|
||||
|
||||
The next time you build or refresh your application's environment, `Scott` will be installed automatically into the active virtual environment.
|
||||
|
||||
```sh
|
||||
cd /your/application/project/root
|
||||
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
|
||||
python -m build
|
||||
```
|
||||
OR
|
||||
```sh
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
## Option 3: Install a local editable copy
|
||||
|
||||
Use this option when you want to modify `Scott` while developing against an application that depends on it.
|
||||
|
||||
First, clone the `Scott` repository to a local working directory:
|
||||
|
||||
```sh
|
||||
cd /your/working/directory
|
||||
|
||||
git clone https://rprime.indroneel.co/termhole/scott.git
|
||||
```
|
||||
|
||||
Then install that checkout in editable mode from your application project:
|
||||
|
||||
```sh
|
||||
cd /your/application/project/root
|
||||
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
|
||||
pip install -e /your/working/directory/scott
|
||||
```
|
||||
|
||||
This makes the installed package point to your local source tree, so changes in `Scott` are picked up immediately. After that, you can either build your application package or install your app in editable mode from its own project directory:
|
||||
|
||||
```sh
|
||||
python -m build
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```sh
|
||||
pip install -e .
|
||||
```
|
||||
+39
-38
@@ -4,50 +4,50 @@ import inspect
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
"""
|
||||
""" =====
|
||||
Command-line application support for dynamically loaded subcommands.
|
||||
|
||||
The :class:`Scott` class provides the common command-line infrastructure for the package. It owns
|
||||
the ``ArgumentParser``, loads command implementations on demand, and dispatches parsed arguments to
|
||||
the selected command module.
|
||||
|
||||
Each command is expected to be available as ``modules.<name>.command`` and to provide a callable
|
||||
``scott_run(args)`` function. A command module may also provide ``scott_description()`` for its help
|
||||
text and ``scott_arguments(parser)`` for command-specific options. Modules that cannot be imported
|
||||
or do not provide a callable ``scott_run`` function are skipped during registration.
|
||||
Each command is expected to be available as ``commands.<name>.handler`` and to provide a callable
|
||||
``s_run(args)`` function. A command handler may also provide ``s_description()`` for its help text
|
||||
and ``s_arguments(parser)`` for command-specific options. Handlers that cannot be imported or do not
|
||||
provide a callable ``s_run`` function are skipped during registration.
|
||||
|
||||
Typical usage from an application entry point is::
|
||||
Typical usage from an application entry point is:
|
||||
|
||||
scott = Scott(__file__, app_desc="A toolset to manage something")
|
||||
for command in commands:
|
||||
scott.register_command(command)
|
||||
for cmd in commands:
|
||||
scott.register(cmd)
|
||||
scott.run()
|
||||
|
||||
The application entry point is responsible for defining the command names. Once ``run()`` is called,
|
||||
``Scott`` parses the process arguments, validates the selected command, displays parser help for
|
||||
invalid input, and invokes the selected module's ``scott_run(args)`` function.
|
||||
"""
|
||||
invalid input, and invokes the selected module's ``s_run(args)`` function.
|
||||
===== """
|
||||
|
||||
class Scott:
|
||||
|
||||
"""
|
||||
""" =====
|
||||
Initialize Scott and its argument parser.
|
||||
Parameters:
|
||||
app_dir (str): The directory where the application script is located. This is used to set up
|
||||
the Python path and to resolve relative paths for subcommand modules.
|
||||
the Python path and to resolve relative paths for command modules.
|
||||
app_desc (str): Optional description for the application, used in the argument parser help.
|
||||
"""
|
||||
===== """
|
||||
|
||||
def __init__(self, app_dir: str, app_desc: str = ""):
|
||||
self.script_dir = Path(app_dir).resolve().parent
|
||||
|
||||
# Ensure the script directory is on Python's import path so local subcommand modules can be
|
||||
# Ensure the script directory is on Python's import path so local command modules can be
|
||||
# imported by name even when this script is executed from another working directory.
|
||||
script_dir_str = str(self.script_dir)
|
||||
if script_dir_str not in sys.path:
|
||||
sys.path.insert(0, script_dir_str)
|
||||
|
||||
self.modules = {}
|
||||
self.commands = {}
|
||||
self.subparsers_by_command = {}
|
||||
|
||||
# prepare the argument parser and subparser collection for command registration
|
||||
@@ -55,73 +55,74 @@ class Scott:
|
||||
self.parser.description = app_desc
|
||||
self.subparsers = self.parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
"""
|
||||
Register one subcommand by dynamically importing its module.
|
||||
""" =====
|
||||
Register one command by dynamically importing its module.
|
||||
Parameters:
|
||||
command (str): The name of the subcommand to register. This is used to construct the module
|
||||
path as ``modules.<command-name>.command``.
|
||||
"""
|
||||
command (str): The name of the command to register. This is used to construct the handler
|
||||
path as ``commands.<command-name>.handler``.
|
||||
===== """
|
||||
|
||||
def register_command(self, cmd_name: str):
|
||||
def register(self, cmd_name: str):
|
||||
try:
|
||||
module_path = f"modules.{cmd_name}.command"
|
||||
module_path = f"commands.{cmd_name}.handler"
|
||||
module = importlib.import_module(module_path)
|
||||
scott_run = getattr(module, "scott_run", None)
|
||||
if not callable(scott_run):
|
||||
s_run = getattr(module, "s_run", None)
|
||||
if not callable(s_run):
|
||||
print(
|
||||
f"Warning: ({cmd_name}) missing a scott_run() function, skipping registration.",
|
||||
f"Warning: ({cmd_name}) missing a s_run() function, skipping registration.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return
|
||||
try:
|
||||
parameter_count = len(inspect.signature(scott_run).parameters)
|
||||
parameter_count = len(inspect.signature(s_run).parameters)
|
||||
except (TypeError, ValueError):
|
||||
parameter_count = 0
|
||||
if parameter_count != 1:
|
||||
print(
|
||||
f"Warning: ({cmd_name}) scott_run() must take exactly one argument, skipping registration.",
|
||||
f"Warning: ({cmd_name}) s_run() must take exactly one argument, skipping registration.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return
|
||||
|
||||
# store the module for later dispatch when the command is invoked
|
||||
self.modules[cmd_name] = module
|
||||
self.commands[cmd_name] = module
|
||||
|
||||
# create a subparser for the command and allow the module to add its own arguments
|
||||
subparser = self.subparsers.add_parser(
|
||||
cmd_name,
|
||||
help = module.scott_description() if hasattr(module, "scott_description") else None,
|
||||
help = module.s_description() if hasattr(module, "s_description") else None,
|
||||
formatter_class=argparse.RawTextHelpFormatter
|
||||
)
|
||||
self.subparsers_by_command[cmd_name] = subparser
|
||||
if hasattr(module, "scott_arguments"):
|
||||
module.scott_arguments(subparser)
|
||||
if hasattr(module, "s_arguments"):
|
||||
module.s_arguments(subparser)
|
||||
except ModuleNotFoundError as error:
|
||||
print(
|
||||
f"Warning: ({cmd_name}) Error loading command script\n{error}\nskipping registration.",
|
||||
f"Warning: ({cmd_name}) Error loading handler\n{error}\nskipping registration.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
"""
|
||||
Parse arguments and execute the selected subcommand.
|
||||
"""
|
||||
""" =====
|
||||
Parse arguments and execute the selected command.
|
||||
===== """
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
args = self.parser.parse_args()
|
||||
args.app_root = self.script_dir
|
||||
except SystemExit as error:
|
||||
# if error.code != 0:
|
||||
# self.parser.print_help()
|
||||
raise
|
||||
|
||||
if args.command not in self.modules:
|
||||
if args.command not in self.commands:
|
||||
print(f"Error: command '{args.command}' does not exist.", file=sys.stderr)
|
||||
self.parser.print_help()
|
||||
return
|
||||
|
||||
selected_module = self.modules[args.command]
|
||||
selected_module = self.commands[args.command]
|
||||
try:
|
||||
selected_module.scott_run(args)
|
||||
selected_module.s_run(args)
|
||||
except Exception as error:
|
||||
print("\n!! Error Encountered !!", file=sys.stderr)
|
||||
print(f"({args.command}): {error}", file=sys.stderr)
|
||||
|
||||
@@ -1,311 +0,0 @@
|
||||
# Scott — Usage Guide
|
||||
|
||||
**scott** is a framework for creating scoped, task-oriented terminal tools. It wraps
|
||||
Python's `argparse` and adds a dynamic subcommand system: each subcommand lives in its
|
||||
own module, is loaded on demand, declares its own CLI options, and is dispatched by the
|
||||
framework. You write small, self-contained command modules; Scott handles argument
|
||||
parsing, help text, validation, and error reporting.
|
||||
|
||||
---
|
||||
|
||||
## 1. Installation
|
||||
|
||||
Scott is a standard setuptools package. From the package root:
|
||||
|
||||
```sh
|
||||
# create and activate a virtual environment (recommended)
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
|
||||
# build a distributable wheel/sdist
|
||||
pip install --upgrade build
|
||||
python -m build
|
||||
|
||||
# install the built wheel
|
||||
pip install dist/scott-1.0-*.whl
|
||||
|
||||
# ...or install in editable mode for development
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
Once installed, import the framework with:
|
||||
|
||||
```python
|
||||
from scott import Scott
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Anatomy of a Scott tool
|
||||
|
||||
A Scott application is a plain Python script (the *entry point*) plus a `modules/`
|
||||
directory of subcommand packages, laid out like this:
|
||||
|
||||
```
|
||||
my-tool/
|
||||
├── my-tool.py # entry point script
|
||||
└── modules/
|
||||
├── cleanup/
|
||||
│ └── command.py # implements the `cleanup` subcommand
|
||||
├── pack/
|
||||
│ └── command.py # implements the `pack` subcommand
|
||||
└── unpack/
|
||||
└── command.py # implements the `unpack` subcommand
|
||||
```
|
||||
|
||||
Each subcommand name maps to `modules/<name>/command.py`. The entry point registers the
|
||||
commands it wants to expose, and Scott imports and dispatches them dynamically.
|
||||
|
||||
### 2.1 The entry point
|
||||
|
||||
```python
|
||||
from scott import Scott
|
||||
|
||||
|
||||
def main():
|
||||
# app_dir: path of this script — Scott resolves it to locate the modules/ directory
|
||||
# app_desc: description shown in the tool's help output
|
||||
scott = Scott(__file__, "A toolset to manage EPUB files")
|
||||
|
||||
commands = [
|
||||
"cleanup",
|
||||
"pack",
|
||||
"unpack",
|
||||
]
|
||||
for command in commands:
|
||||
scott.register_command(command)
|
||||
|
||||
scott.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
Running the tool:
|
||||
|
||||
```sh
|
||||
$ python my-tool.py --help
|
||||
usage: my-tool.py [-h] {cleanup,pack,unpack} ...
|
||||
|
||||
A toolset to manage EPUB files
|
||||
|
||||
positional arguments:
|
||||
{cleanup,pack,unpack}
|
||||
cleanup This will cleanup
|
||||
pack This will pack
|
||||
unpack This will unpack
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. The command module contract
|
||||
|
||||
Every command module (`modules/<name>/command.py`) is a plain Python module. Scott
|
||||
recognizes the following functions:
|
||||
|
||||
| Function | Required | Purpose |
|
||||
| ------------------------- | -------- | ------------------------------------------------------------------------ |
|
||||
| `scott_run(args)` | **Yes** | The command's entry point. Called with the parsed `argparse` namespace. |
|
||||
| `scott_description()` | Optional | Returns a short help string shown in the command list. |
|
||||
| `scott_arguments(parser)` | Optional | Registers command-specific options on the command's subparser. |
|
||||
|
||||
### 3.1 `scott_run(args)` — required
|
||||
|
||||
The command's main function. It **must accept exactly one argument** (the parsed
|
||||
`argparse` namespace); registration is skipped with a warning otherwise.
|
||||
|
||||
```python
|
||||
def scott_run(args):
|
||||
# args contains any options registered via scott_arguments(),
|
||||
# plus args.command (the subcommand name)
|
||||
print("command: pack")
|
||||
```
|
||||
|
||||
### 3.2 `scott_description()` — optional
|
||||
|
||||
Returns a one-line description used as the command's help text in the parent help
|
||||
listing.
|
||||
|
||||
```python
|
||||
def scott_description():
|
||||
return "This will pack"
|
||||
```
|
||||
|
||||
### 3.3 `scott_arguments(parser)` — optional
|
||||
|
||||
Receives the command's `argparse` subparser so the command can define its own positional
|
||||
arguments and options. They arrive in `args` at dispatch time.
|
||||
|
||||
```python
|
||||
def scott_arguments(parser):
|
||||
parser.add_argument(
|
||||
"file_path",
|
||||
help="The path where the file to be unpacked."
|
||||
)
|
||||
```
|
||||
|
||||
A complete command module:
|
||||
|
||||
```python
|
||||
# modules/unpack/command.py
|
||||
|
||||
def scott_description():
|
||||
return "This will unpack"
|
||||
|
||||
def scott_arguments(parser):
|
||||
parser.add_argument(
|
||||
"file_path",
|
||||
help="The path where the file to be unpacked."
|
||||
)
|
||||
|
||||
def scott_run(args):
|
||||
print(f"command: unpack, file: {args.file_path}")
|
||||
```
|
||||
|
||||
Which produces:
|
||||
|
||||
```sh
|
||||
$ python my-tool.py unpack --help
|
||||
usage: my-tool.py unpack [-h] file_path
|
||||
|
||||
positional arguments:
|
||||
file_path The path where the file to be unpacked.
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. API reference
|
||||
|
||||
### `Scott(app_dir: str, app_desc: str = "")`
|
||||
|
||||
Creates the framework and its argument parser.
|
||||
|
||||
- `app_dir` — typically `__file__` from the entry script. Scott resolves it to the
|
||||
containing directory, which is used to (a) locate the `modules/` packages and (b) is
|
||||
prepended to `sys.path` so the tool works no matter which directory you invoke it from.
|
||||
- `app_desc` — description shown at the top of the tool's help output.
|
||||
|
||||
### `Scott.register_command(cmd_name: str)`
|
||||
|
||||
Registers a subcommand by dynamically importing `modules.<cmd_name>.command`. During
|
||||
registration Scott:
|
||||
|
||||
1. Imports the module; if it cannot be imported, prints a warning to *stderr* and skips
|
||||
the command.
|
||||
2. Verifies `scott_run` exists, is callable, and takes **exactly one** parameter;
|
||||
otherwise warns to *stderr* and skips the command.
|
||||
3. Creates an `argparse` subparser named `cmd_name`, using `scott_description()` (if
|
||||
present) as its help text.
|
||||
4. Calls `module.scott_arguments(subparser)` (if present) so the command can add options.
|
||||
|
||||
Skipped commands never appear in help output and cannot be invoked.
|
||||
|
||||
### `Scott.run()`
|
||||
|
||||
Parses the process arguments and dispatches to the selected command's
|
||||
`scott_run(args)`. Behavior on failure is covered in the next section.
|
||||
|
||||
---
|
||||
|
||||
## 5. Error handling and exit codes
|
||||
|
||||
| Situation | Behavior | Exit code |
|
||||
| --------------------------------------- | -------------------------------------------------------------------------------------------- | --------- |
|
||||
| Command runs successfully | Normal output. | `0` |
|
||||
| Exception raised inside `scott_run` | Prints `!! Error Encountered !!`, `(command): <error>`, and the command's help to *stderr*. | `0` |
|
||||
| Unknown command / missing required args | argparse error message, then the tool's full help is printed. | `2` |
|
||||
| No command given | Help is printed (a command is **required**). | `2` |
|
||||
|
||||
Example of a command that raised an exception:
|
||||
|
||||
```sh
|
||||
$ python my-tool.py unpack /tmp/book.epub
|
||||
command: unpack
|
||||
|
||||
!! Error Encountered !!
|
||||
(unpack): The unpack command is not yet implemented.
|
||||
usage: my-tool.py unpack [-h] file_path
|
||||
|
||||
positional arguments:
|
||||
file_path The path where the file to be unpacked.
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
```
|
||||
|
||||
Note that errors inside a command are caught and reported but do not propagate — the
|
||||
process still exits `0`. Commands that need to signal failure should handle it
|
||||
themselves (e.g. via `sys.exit(1)` inside `scott_run`).
|
||||
|
||||
---
|
||||
|
||||
## 6. A complete, minimal example
|
||||
|
||||
```
|
||||
hello-tool/
|
||||
├── hello-tool.py
|
||||
└── modules/
|
||||
└── greet/
|
||||
└── command.py
|
||||
```
|
||||
|
||||
`hello-tool.py`:
|
||||
|
||||
```python
|
||||
from scott import Scott
|
||||
|
||||
|
||||
def main():
|
||||
scott = Scott(__file__, "A tiny Scott-powered tool")
|
||||
scott.register_command("greet")
|
||||
scott.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
`modules/greet/command.py`:
|
||||
|
||||
```python
|
||||
def scott_description():
|
||||
return "Greet someone"
|
||||
|
||||
def scott_arguments(parser):
|
||||
parser.add_argument("name", help="Who to greet")
|
||||
|
||||
def scott_run(args):
|
||||
print(f"Hello, {args.name}!")
|
||||
```
|
||||
|
||||
Run it:
|
||||
|
||||
```sh
|
||||
$ python hello-tool.py greet World
|
||||
Hello, World!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Notes
|
||||
|
||||
- **Work from any directory.** The entry script's directory is added to `sys.path`
|
||||
automatically, so `python /path/to/my-tool.py pack` works from anywhere.
|
||||
- **Commands are loaded at registration.** Modules are imported once, when
|
||||
`register_command()` is called, and reused for dispatch; only registered commands are
|
||||
loaded.
|
||||
- **Bytecode is disabled.** Scott sets `sys.dont_write_bytecode = True` on import, so no
|
||||
`__pycache__` directories are created for the framework or your modules.
|
||||
- **Layout matters.** The `modules/` directory must be a sibling of the entry script, and
|
||||
each command must be a package directory named exactly like the command
|
||||
(`modules/<name>/command.py`).
|
||||
- **License.** Scott is distributed under the DuxTechnica Limited Use Source Code License
|
||||
Agreement (DT-LUSCL) — see `LICENSE` for details.
|
||||
|
||||
Reference in New Issue
Block a user