CLI Tool with argparse
Build a professional CLI tool with subcommands, typed arguments, environment variable fallbacks, and help text.
import argparse
import os
import sys
def cmd_init(args: argparse.Namespace) -> None:
print(f"Initializing project: {args.name}")
print(f"Template: {args.template}")
def cmd_deploy(args: argparse.Namespace) -> None:
print(f"Deploying to {args.environment}")
if args.dry_run:
print("(dry run — no changes made)")
def main() -> int:
parser = argparse.ArgumentParser(
prog="mytool",
description="A production CLI tool example",
)
parser.add_argument(
"--verbose", "-v", action="store_true", help="Enable verbose output"
)
subparsers = parser.add_subparsers(dest="command", required=True)
# init subcommand
init_parser = subparsers.add_parser("init", help="Initialize a new project")
init_parser.add_argument("name", help="Project name")
init_parser.add_argument(
"--template", "-t", default="default", choices=["default", "minimal", "full"]
)
init_parser.set_defaults(func=cmd_init)
# deploy subcommand
deploy_parser = subparsers.add_parser("deploy", help="Deploy the project")
deploy_parser.add_argument(
"--environment", "-e",
default=os.getenv("DEPLOY_ENV", "staging"),
choices=["staging", "production"],
)
deploy_parser.add_argument("--dry-run", action="store_true")
deploy_parser.set_defaults(func=cmd_deploy)
args = parser.parse_args()
args.func(args)
return 0
if __name__ == "__main__":
sys.exit(main())
# Usage:
# python cli.py init my-project --template full
# python cli.py deploy --environment production --dry-runUse Cases
- Developer tooling
- Build scripts
- Data pipeline runners
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Click CLI Command Group
Build professional CLI tools with Click using command groups, options, arguments, and help text.
Rich Progress Bar for CLI
Display beautiful progress bars and status spinners in CLI applications using the Rich library.
Async HTTP Client with httpx
Production-ready async HTTP client using httpx with retries, timeouts, and connection pooling.
Retry Decorator with Exponential Backoff
Generic retry decorator with configurable attempts, exponential backoff, and exception filtering.