Skip to content

Python: Argparse Command-Line Parsing

#!/usr/bin/env python
import argparse
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def parse_args():
parser = argparse.ArgumentParser(
description="Example script demonstrating argparse features"
)
# Required argument with custom destination
parser.add_argument(
"--arg",
dest="arg_weird_dest",
required=True,
help="A required argument with custom destination name"
)
# Boolean flag (defaults to False)
parser.add_argument(
"--flg",
action="store_true",
help="Enable a feature (flag is False by default)"
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
logger.info(f"Argument value: {args.arg_weird_dest}")
logger.info(f"Flag enabled: {args.flg}")
import argparse
parser = argparse.ArgumentParser()
# Positional argument (required by default)
parser.add_argument("input_file", help="Path to input file")
# Optional argument with default value
parser.add_argument("--output", default="output.txt", help="Output file path")
# Integer argument
parser.add_argument("--count", type=int, default=10, help="Number of iterations")
# Float argument
parser.add_argument("--threshold", type=float, default=0.5, help="Threshold value")
# Multiple values
parser.add_argument("--files", nargs="+", help="One or more file paths")
# Choice from a list
parser.add_argument(
"--format",
choices=["json", "yaml", "xml"],
default="json",
help="Output format"
)
# Store constant value
parser.add_argument(
"--verbose", "-v",
action="store_const",
const=logging.DEBUG,
default=logging.INFO,
help="Enable verbose logging"
)
args = parser.parse_args()
import argparse
def cmd_create(args):
print(f"Creating resource: {args.name}")
if args.force:
print("Force mode enabled")
def cmd_delete(args):
print(f"Deleting resource: {args.name}")
if args.confirm:
print("Confirmed deletion")
parser = argparse.ArgumentParser(description="Resource management CLI")
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Create subcommand
create_parser = subparsers.add_parser("create", help="Create a new resource")
create_parser.add_argument("name", help="Resource name")
create_parser.add_argument("--force", action="store_true", help="Force creation")
create_parser.set_defaults(func=cmd_create)
# Delete subcommand
delete_parser = subparsers.add_parser("delete", help="Delete a resource")
delete_parser.add_argument("name", help="Resource name")
delete_parser.add_argument("--confirm", action="store_true", help="Confirm deletion")
delete_parser.set_defaults(func=cmd_delete)
args = parser.parse_args()
if hasattr(args, "func"):
args.func(args)
else:
parser.print_help()
import argparse
parser = argparse.ArgumentParser()
# Only one of these can be specified
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--read", action="store_true", help="Read mode")
group.add_argument("--write", action="store_true", help="Write mode")
group.add_argument("--delete", action="store_true", help="Delete mode")
args = parser.parse_args()
import argparse
import os
def valid_file(path):
"""Custom validator for file paths"""
if not os.path.isfile(path):
raise argparse.ArgumentTypeError(f"{path} is not a valid file")
return path
def valid_port(value):
"""Custom validator for port numbers"""
ivalue = int(value)
if ivalue < 1 or ivalue > 65535:
raise argparse.ArgumentTypeError(f"{value} is not a valid port (1-65535)")
return ivalue
parser = argparse.ArgumentParser()
parser.add_argument("--config", type=valid_file, help="Configuration file path")
parser.add_argument("--port", type=valid_port, default=8080, help="Server port")
args = parser.parse_args()