Commands
Define Model
commands.py
"""Commands Example."""
import pydantic.v1 as pydantic
import pydantic_argparse
from typing import Optional
class BuildCommand(pydantic.BaseModel):
"""Build Command Arguments."""
# Required Args
location: pydantic.FilePath = pydantic.Field(description="build location")
class ServeCommand(pydantic.BaseModel):
"""Serve Command Arguments."""
# Required Args
address: pydantic.IPvAnyAddress = pydantic.Field(description="serve address")
port: int = pydantic.Field(description="serve port")
class Arguments(pydantic.BaseModel):
"""Command-Line Arguments."""
# Optional Args
verbose: bool = pydantic.Field(False, description="verbose flag")
# Commands
build: Optional[BuildCommand] = pydantic.Field(description="build command")
serve: Optional[ServeCommand] = pydantic.Field(description="serve command")
def main() -> None:
"""Main Function."""
# Create Parser and Parse Args
parser = pydantic_argparse.ArgumentParser(
model=Arguments,
prog="Example Program",
description="Example Description",
version="0.0.1",
epilog="Example Epilog",
)
args = parser.parse_typed_args()
# Print Args
print(args)
if __name__ == "__main__":
main()
Check Help
$ python3 examples/commands.py --help
usage: Example Program [-h] [-v] [--verbose] {build,serve} ...
Example Description
commands:
{build,serve}
build build command
serve serve command
optional arguments:
--verbose verbose flag (default: False)
help:
-h, --help show this help message and exit
-v, --version show program's version number and exit
Example Epilog
Check Commands Help
$ python3 examples/commands.py build --help
usage: Example Program build [-h] --location LOCATION
required arguments:
--location LOCATION build location
help:
-h, --help show this help message and exit
$ python3 examples/commands.py serve --help
usage: Example Program serve [-h] --address ADDRESS --port PORT
required arguments:
--address ADDRESS serve address
--port PORT serve port
help:
-h, --help show this help message and exit
Parse Arguments
$ python3 examples/commands.py --verbose serve --address 127.0.0.1 --port 8080
verbose=True build=None serve=ServeCommand(address=IPv4Address('127.0.0.1'), port=8080)