Mini Project: CLI Tool with argparse
Build a command-line tool using Python's built-in argparse module. Create professional CLI interfaces with arguments, options, and help text.
20 min•By Priygop Team•Updated 2026
CLI Tool with argparse
CLI Tool with argparse
import argparse
import sys
def parse_args(args=None):
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description="File Utils — A Python CLI tool",
epilog="Example: python file_utils.py count -f readme.txt"
)
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Count command
count_parser = subparsers.add_parser("count", help="Count words/lines in text")
count_parser.add_argument("text", help="Text to analyze")
count_parser.add_argument("--lines", action="store_true", help="Count lines instead")
# Search command
search_parser = subparsers.add_parser("search", help="Search for a pattern")
search_parser.add_argument("pattern", help="Pattern to search for")
search_parser.add_argument("text", help="Text to search in")
search_parser.add_argument("-i", "--ignore-case", action="store_true")
# Format command
format_parser = subparsers.add_parser("format", help="Format text")
format_parser.add_argument("text", help="Text to format")
format_parser.add_argument("--upper", action="store_true")
format_parser.add_argument("--reverse", action="store_true")
return parser.parse_args(args)
def main():
# Demo with simulated arguments
demos = [
["count", "Hello World Python is great"],
["count", "--lines", "Line1\nLine2\nLine3"],
["search", "python", "I love Python programming", "-i"],
["format", "hello world", "--upper"],
["format", "hello world", "--reverse"],
]
for demo_args in demos:
args = parse_args(demo_args)
print(f"Command: {' '.join(demo_args)}")
if args.command == "count":
if args.lines:
count = args.text.count("\n") + 1
print(f" Lines: {count}")
else:
count = len(args.text.split())
print(f" Words: {count}")
elif args.command == "search":
text = args.text.lower() if args.ignore_case else args.text
pattern = args.pattern.lower() if args.ignore_case else args.pattern
found = pattern in text
print(f" Found '{args.pattern}': {found}")
elif args.command == "format":
result = args.text
if args.upper: result = result.upper()
if args.reverse: result = result[::-1]
print(f" Result: {result}")
print()
if __name__ == "__main__":
main()Tip
Tip
Structure projects with src/, tests/, docs/ folders. Use pyproject.toml for modern Python project configuration.
Diagram
Loading diagram…
Module = file, Package = folder + __init__.py, Library = pip.
Common Mistake
Warning
Putting everything in one file. Split into modules when a file exceeds 300 lines. It improves readability and testability.
Quick Quiz
Practice Task
Note
(1) Create a project with proper structure. (2) Add __init__.py, requirements.txt, README.md. (3) Make it installable with setup.py.