Automatically generate CLI from Pydantic models
Project description
pydantic-autocli
Automatically generate sub-command based CLI applications from Pydantic models.
Installation
pip install pydantic-autocli
Features
- Automatically generate CLI commands from class methods
- Map Pydantic model fields to CLI arguments
- Customize CLI arguments with short/long forms and other options
- Automatically handle help text generation
- Support for common arguments across all commands
- Support for async commands
- Support for array arguments (list[str], list[int], list[float], etc.)
Basic Usage
pydantic-autocli provides multiple ways to define CLI arguments and commands.
from pydantic import BaseModel
from pydantic_autocli import AutoCLI, param
class MyCLI(AutoCLI):
class CommonArgs(AutoCLI.CommonArgs):
# Common arguments for all commands and act as a fallback
verbose: bool = param(False, l="--verbose", s="-v", description="Enable detailed output")
seed: int = 42
# Executed commonly for all subcommands
def pre_common(self, args:CommonArgs):
print('Using seed: {args.seed}')
# Standard Pydantic notation
class SimpleArgs(CommonArgs):
# Required parameter (no default value)
required_value: int
# Optional parameter (with default value)
optional_value: int = 123
# Array parameter
names: list[str] = []
# This method will automatically use SimpleArgs
# Args class selection rule: run_simple -> SimpleArgs (by naming convention)
def run_simple(self, args):
"""Execute simple command"""
print(f"Required: {args.required_value}")
print(f"Optional: {args.optional_value}")
print(f"Names: {args.names}")
class CustomAdvancedArgs(CommonArgs):
# file_name becomes --file-name in command line
file_name: str
# Restrict choices
mode: str = param("read", l="--mode", choices=["read", "write", "append"])
wait: float = 0.5
# This method will use CustomAdvancedArgs
# Args class is explicitly specified (by type annotation)
# This is an async method that can be awaited
async def run_advanced(self, args:CustomAdvancedArgs):
"""Execute advanced command"""
print(f"Mode: {args.mode}")
print(f"Filenames: {args.file_names}")
print(f"Numbers: {args.numbers}")
import asyncio
print(f"Awaiting for {args.wait}s..")
await asyncio.sleep(args.wait)
if args.verbose:
print("Verbose mode enabled")
if not os.path.exists(args.file_name):
return False # Indicates error (exit code 1)
return True # Indicates success (exit code 0)
# Also supports custom exit codes
# return 423
if __name__ == "__main__":
cli = MyCLI()
cli.run() # Uses sys.argv by default
# cli.run(sys.argv) # Explicitly pass sys.argv
# Pass custom arguments
# cli.run(["program_name", "command", "--value", "value1", "--flag"])
Command-line execution examples
# Run simple command with required parameter
python your_script.py run-simple --required-value 42
# Run simple command with all parameters
python your_script.py run-simple --required-value 42 --optional-value 100 --names "John Jane"
# Run advanced command
python your_script.py run-advanced --file-name data.txt --mode write --wait 1.5 --verbose
Argument Resolution
Using Naming Convention
You can specify argument classes for CLI commands using naming conventions:
class MyCLI(AutoCLI):
# Naming convention:
# run_command → CommandArgs
# run_foo_bar → FooBarArgs
# Single-word command example
class CommandArgs(AutoCLI.CommonArgs):
name: str = param("default", l="--name", s="-n")
def run_command(self, args):
print(f"Name: {args.name}")
return True # Indicates success (exit code 0)
# Two-word command example
class FooBarArgs(AutoCLI.CommonArgs):
option: str = param("default", l="--option")
def run_foo_bar(self, args):
print(f"Option: {args.option}")
return True # Indicates success (exit code 0)
Using Type Annotations
You can directly specify the argument class using type annotations:
from pydantic import BaseModel
from pydantic_autocli import AutoCLI, param
class MyCLI(AutoCLI):
class CustomArgs(BaseModel):
value: int = param(42, l="--value", s="-v")
flag: bool = param(False, l="--flag", s="-f")
# Use type annotation to specify args class
def run_command(self, args: CustomArgs):
print(f"Value: {args.value}")
if args.flag:
print("Flag is set")
return True
Resolution Priority
pydantic-autocli uses the following priority order to determine which argument class to use:
- Type annotation on the method parameter
- Naming convention (CommandArgs class for run_command method)
- Fall back to CommonArgs
When both naming convention and type annotation could apply to a method, the type annotation takes precedence (as per the priority above). In such cases, a warning is displayed about the conflict:
class MyCLI(AutoCLI):
# Args class that follows naming convention
class CommandArgs(BaseModel):
name: str = param("default", l="--name")
# Different args class specified by type annotation
class CustomArgs(BaseModel):
value: int = param(42, l="--value")
# Type annotation takes precedence over naming convention
# A warning will be displayed about the conflict
def run_command(self, args: CustomArgs):
# Uses CustomArgs even though CommandArgs exists
print(f"Value: {args.value}")
return True
This command will use CustomArgs (from type annotation) instead of CommandArgs (from naming convention), with a warning about the detected conflict.
Development and Testing
# Install development dependencies
uv sync --dev
# Run tests
uv run pytest
# Or using taskipy
uv run task test
Examples
To run the example CLI:
python examples/example.py greet --verbose
# Or using taskipy
uv run task example file --file README.md
License
See LICENSE file.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pydantic_autocli-0.1.5.tar.gz.
File metadata
- Download URL: pydantic_autocli-0.1.5.tar.gz
- Upload date:
- Size: 54.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
883c751ef11c3b4ec25fdc57f193fdb8c9191a8183c0b0c08ce322aea131dcc1
|
|
| MD5 |
f84fa0dbe078805bb902eb01c50bb357
|
|
| BLAKE2b-256 |
a49e8f912431b149facb74294f008996260e1ce3e18eabaafa7f05bfa28b6402
|
File details
Details for the file pydantic_autocli-0.1.5-py3-none-any.whl.
File metadata
- Download URL: pydantic_autocli-0.1.5-py3-none-any.whl
- Upload date:
- Size: 10.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
88d3903d2878223b99cc7c92a7363b1a93b60a83fbf0fa693fc035ca0da6da06
|
|
| MD5 |
82301b6aecc415bc1490c0b39f65e789
|
|
| BLAKE2b-256 |
eaeeb111c63e9fa38c00c7534278fda43661cf16527a41136c9cadf784efedfe
|