
How to Create a CLI Tool with Python and argparse
Command-line interface (CLI) tools are powerful for automating tasks and creating user-friendly scripts. Whether you’re building internal utilities or open-source tools, Python makes it incredibly easy—especially with the built-in argparse module.
In this guide, you’ll learn how to create your own CLI tool using argparse with clear, beginner-friendly examples.
What Is a CLI Tool?
A CLI (Command-Line Interface) tool is a script or program that accepts user input via command-line arguments. Instead of a GUI, users interact with it by typing commands like:
bash
Copy code
python tool.py –name Alice –greet
Why Use argparse?
- Built-in (no installation needed)
- Simple to use
- Automatically generates help messages
- Supports positional and optional arguments
Creating a Simple CLI Tool
Let’s create a basic greeting script that uses user-provided arguments:
python
Copy code
import argparse
parser = argparse.ArgumentParser(description=”A simple greeting CLI tool”)
parser.add_argument(‘–name’, type=str, help=’Your name’)
parser.add_argument(‘–greet’, action=’store_true’, help=’Print a greeting’)
args = parser.parse_args()
if args.greet and args.name:
print(f”Hello, {args.name}!”)
else:
print(“Use –greet and –name to get a greeting.”)
Run it like this:
bash
Copy code
python greet.py –name Alice –greet
Output:
Copy code
Hello, Alice!
Positional vs Optional Arguments
- Positional: Required and order-dependent
- Optional: Use — prefix and can appear in any order
Example:
python
Copy code
parser.add_argument(‘filename’, help=’The file to process’)
Adding Default Values and Choices
python
Copy code
parser.add_argument(‘–lang’, choices=[‘en’, ‘es’], default=’en’, help=’Language option’)
This ensures users can only input en or es, with en as the default.
Auto Help Message
argparse automatically adds a –help option:
bash
Copy code
python greet.py –help
Output:
less
Copy code
usage: greet.py [-h] [–name NAME] [–greet]
optional arguments:
-h, –help show this help message and exit
–name NAME Your name
–greet Print a greeting
Real-World Use Case: File Analyzer CLI
python
Copy code
import argparse
import os
def count_lines(filepath):
with open(filepath, ‘r’) as file:
return len(file.readlines())
parser = argparse.ArgumentParser(description=”File line counter”)
parser.add_argument(‘file’, help=’Path to the file’)
args = parser.parse_args()
if os.path.exists(args.file):
print(f”{args.file} has {count_lines(args.file)} lines.”)
else:
print(“File does not exist.”)
Practice Challenge
Create a CLI tool that takes a filename and a keyword, then counts how many times the keyword appears in the file.
Why It Matters
Creating CLI tools can:
- Automate repetitive tasks
- Improve productivity
- Help you contribute to developer tooling
- Showcase practical Python skills in portfolios or jobs
Take the Next Step
Now that you know how to create CLI tools with argparse, try building your own! You’ll not only deepen your Python knowledge but also create something genuinely useful.
🚀 For project-based Python learning, visit
👉 https://www.thefullstack.co.in/courses/
You might be like this:-
What is AWS Lambda?A Beginner’s Guide to Serverless Computing in 2025
Java vs. Kotlin: Which One Should You Learn for Backend Development?
Leave a Reply