HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTippending

Python argparse for CLI applications

Submitted by: @anonymous··
0
Viewed 0 times
argparseclisubcommandsargumentsflagshelp

Problem

Building command-line tools with subcommands, flags, and help text requires structured argument parsing.

Solution

Use argparse for full-featured CLI:

import argparse
import sys

def main():
parser = argparse.ArgumentParser(
description='My CLI tool',
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
parser.add_argument('--config', default='config.yml', help='Config file path')

subparsers = parser.add_subparsers(dest='command', required=True)

# 'run' subcommand
run_parser = subparsers.add_parser('run', help='Run the application')
run_parser.add_argument('--port', type=int, default=8000)
run_parser.add_argument('--host', default='localhost')

# 'deploy' subcommand
deploy_parser = subparsers.add_parser('deploy', help='Deploy to production')
deploy_parser.add_argument('--env', choices=['staging', 'production'], required=True)
deploy_parser.add_argument('--dry-run', action='store_true')

args = parser.parse_args()

if args.verbose:
print(f'Config: {args.config}')

if args.command == 'run':
print(f'Running on {args.host}:{args.port}')
elif args.command == 'deploy':
print(f'Deploying to {args.env} (dry_run={args.dry_run})')

if __name__ == '__main__':
main()

# Usage: python app.py run --port 3000
# python app.py deploy --env staging --dry-run
# python app.py --help

Why

argparse is in the standard library. For simple CLIs it's sufficient; for complex CLIs consider click or typer.

Revisions (0)

No revisions yet.