Automatically generate CLI interfaces from function signatures and docstrings
pip install philiprehberger-docstring-cliAutomatically generate CLI interfaces from function signatures and docstrings.
pip install philiprehberger-docstring-cli
@cli decoratorfrom philiprehberger_docstring_cli import cli
@cli
def greet(name: str, count: int = 1, loud: bool = False):
"""Greet someone by name.
Args:
name: The person to greet.
count: Number of times to greet.
loud: Whether to shout.
"""
greeting = f"Hello, {name}!"
if loud:
greeting = greeting.upper()
for _ in range(count):
print(greeting)
# Call from CLI: python greet.py Alice --count 3 --loud
# Or call normally: greet("Alice", count=3, loud=True)
The decorated function can still be called normally with arguments. When called
with no arguments, it parses sys.argv and runs as a CLI command.
Use .cli(argv=[...]) to pass explicit arguments:
greet.cli(["Alice", "--count", "2", "--loud"])
run()For one-off usage without decorating:
from philiprehberger_docstring_cli import run
def add(a: int, b: int):
"""Add two numbers.
Args:
a: First number.
b: Second number.
"""
return a + b
run(add, ["3", "4"]) # prints 7
--versionPass version="..." to run() to enable a built-in --version flag:
from philiprehberger_docstring_cli import run
def add(a: int, b: int):
"""Add two numbers."""
return a + b
run(add, version="1.0.0")
# Invoking with --version prints "1.0.0" and exits.
Use command_info(fn) to inspect a @cli-decorated (or plain) function
without invoking it. Useful for building help screens, completion data,
or programmatic command listings.
from philiprehberger_docstring_cli import cli, command_info
@cli
def greet(name: str, count: int = 1):
"""Greet someone by name.
Args:
name: The person to greet.
count: Number of times to greet.
"""
...
info = command_info(greet)
# {
# "name": "greet",
# "description": "Greet someone by name.",
# "params": [
# {"name": "name", "type": "str", "default": None, "required": True, "help": "The person to greet."},
# {"name": "count", "type": "int", "default": 1, "required": False, "help": "Number of times to greet."},
# ],
# }
| Name | Description |
|---|---|
cli | Decorator that makes a function callable from the CLI. |
run | Run any function as a CLI command without decorating it. |
command_info | Introspect a function and return its CLI metadata. |
@cliint, float, str, etc.)--flagsbool parameters become --flag / --no-flag togglesdry_run -> --dry-run)Args: sections are used for help textrun(func, argv=None, *, version=None)argv (or sys.argv[1:])@cli decoratorversion: when set, the parser accepts --version and prints this stringcommand_info(func)name, description, and paramsparams is a dict with name, type, default, required, and help@cli-decorated functions as well as plain functionspip install -e .
python -m pytest tests/ -v
If you find this project useful: