pythonbeginner
CLI Tool with argparse
Build a professional CLI tool with subcommands, typed arguments, environment variable fallbacks, and help text.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
Click CLI Command Group
Build professional CLI tools with Click using command groups, options, arguments, and help text.
Best for: Developer tools
#cli#click
pythonbeginner
Python CLI Tool with Argparse
Build a command-line tool with subcommands, arguments, validation, and help text using argparse.
Best for: Building developer tooling CLIs
#python#cli
javaintermediate
CLI Argument Parser
Parse command-line arguments with flags, options, positional args, and help text without external libraries.
Best for: Command-line tool argument parsing
#java#cli
scalaintermediate
Command-Line Application
Build CLI applications with argument parsing, interactive prompts, and formatted output.
Best for: Command-line tool development
#scala#cli