Site icon Full-Stack

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?


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

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:


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:-

Python Modules and Packages

What is AWS Lambda?A Beginner’s Guide to Serverless Computing in 2025

Java vs. Kotlin: Which One Should You Learn for Backend Development?

Where to Find Your Salesforce Organization ID

Frequently Asked Questions

What is the best way to get started with creating a CLI tool with Python and argparse?

To get started, you should first install the argparse library, which is part of the Python standard library, so you don’t need to install anything extra. Then, create a new Python script and import the argparse module. You can then start defining your CLI tool’s arguments and options.

How do I define arguments and options for my CLI tool using argparse?

You can define arguments and options using the add_argument method of the ArgumentParser object, which allows you to specify the name, type, and other properties of the argument or option. You can also use the add_argument_group method to group related arguments together. This makes it easy to organize and document your CLI tool’s usage.

How can I handle invalid input or errors in my CLI tool?

To handle invalid input or errors, you can use try-except blocks to catch and handle exceptions raised by the argparse library or your own code. You can also use the parse_args method’s exit_on_error parameter to control whether the program exits when an error occurs. This allows you to provide helpful error messages and usage information to the user.

Can I use argparse to create subcommands for my CLI tool?

<p"Yes, you can use the add_subparsers method of the ArgumentParser object to create subcommands for your CLI tool. This allows you to define a hierarchy of commands and subcommands, making it easy to organize complex functionality. You can then define separate argument parsers for each subcommand, allowing you to customize the usage and behavior of each subcommand.

How can I test and debug my CLI tool to ensure it works correctly?

To test and debug your CLI tool, you can use the argparse library’s built-in support for generating usage messages and help text. You can also use tools like pytest or unittest to write automated tests for your CLI tool, covering different scenarios and edge cases. Additionally, you can use a debugger like pdb to step through your code and inspect variables and function calls.

Exit mobile version