Development

How to Create a Python CLI Tool: Step-by-Step Guide

Creating a command-line interface (CLI) tool in Python can help you automate tasks and share scripts easily. In this tutorial, you’ll build a Python CLI step-by-step – from setting up your environment to packaging the tool for others to use. By the end, you’ll have a working CLI app and knowledge of argparse vs Click, how to handle arguments, and more.

Why Build a CLI Tool Using Python?

First off, why are we even talking about command-line interfaces (CLIs)? Well, think of them as your direct line to a computer, no fancy graphics, just pure, unadulterated commands. You type something in, and bam, the computer does it. It’s like being a wizard but with a keyboard.

They are amazing for automating tasks. Plus, they’re super resource-efficient. You know, back in my early days, I once automated a whole bunch of tedious data processing with a simple Python CLI tool script. It felt like magic, seriously. I saved myself hours of work!

Understanding CLI Tool Execution Flow

Here’s a simple flow diagram illustrating how a typical CLI tool works

  1. User Enters Command: User types a command in the terminal (e.g., git commit -m "message")
  2. Terminal/Shell: Receives and forwards the command to the CLI tool
  3. CLI Tool: The application binary starts processing
  4. Parse Arguments & Flags: Splits the command into components (action, options, arguments)
  5. Valid Input?: Checks syntax, required flags, and argument validity
    • ❌ Invalid → Display Error Message (e.g., “Invalid flag: -z”)
    • ✅ Valid → Proceed to execution
  6. Execute Command: Performs the core operation (e.g., file I/O, network requests, calculations)
  7. Operation Successful?: Checks execution result
    • ❌ Failure → Display Error Message (e.g., “File not found”)
    • ✅ Success → Display Results (output/data)

Now that you have some high-level understanding, let’s dive into the main steps.

#1 Prerequisites and Environment Setup

First, you need Python. (Duh.) If you don’t have it installed, grab it from python.org. I would recommend using Python version 3.8 or newer. To check if Python is installed, run this in your terminal:

python --version
Bash

If you see something like Python 3.10.5, you’re good to go. If not, install it. (Using a Python version manager to manage multiple versions is highly recommended)

Next, let’s make a folder for your project. Fire up your terminal and type:

mkdir my-cli-tool && cd my-cli-tool
Bash

Now, set up a Python virtual environment so your project dependencies don’t mess up your system’s Python. It’s like creating a sandbox. Run:

python -m venv venv
source venv/bin/activate   # On Windows: venv\Scripts\activate
Bash

(Yes, it’s annoying the first few times. Stick with me.)

Pro Tip💡: Learn more in-depth about setting up python local development environment.

#2 Choosing a Python Library for Building CLI Tool:

Python has several libraries for building CLI tools. The big three are:

  1. argparse: Built-in, straightforward, and great for basic tools.
  2. click: User-friendly and fun to use.
  3. typer: A modern library inspired by FastAPI with automatic documentation.

We’ll use click for this guide because it strikes the right balance between power and simplicity. Let’s Install it with:

pip install click
Bash

#3 Writing Your First CLI Tool With Python

Let’s write some code! Open a new file called app.py in your favourite editor. Here’s your starter template:

import click

@click.command()
@click.option('--name', prompt='Your name', help='The name of the user.')
def greet(name):
    """Simple program that greets the user."""
    click.echo(f"Hello, {name}! Welcome to the world of CLI tools.")

if __name__ == '__main__':
    greet()
Bash

What’s Happening Here?

  • @click.command(): Turns the greet function into a CLI command.
  • @click.option(): Adds an option to the CLI. The --name flag makes it optional while prompt asking the user if they don’t provide it.
  • click.echo(): Prints messages in a CLI-friendly way. (It’s just print with some extra flair.)

Now run your tool:

python app.py
Bash

It’ll ask for your name and greet you. Try adding --name like this:

python app.py --name "Sam"
Bash

It should give an output like the following:

Hello, Sam! Welcome to the world of CLI tools.
Bash

Boom! Your first CLI tool. 🎉

#4 Adding Commands to your CLI Tool

What if you want your python CLI tool to do more than one thing? Click makes it easy with command groups. Update app.py:

import click

@click.group()
def cli():
    """A handy CLI tool."""
    pass

@cli.command()
@click.option('--name', prompt='Your name', help='The name of the user.')
def greet(name):
    """Greets the user."""
    click.echo(f"Hello, {name}! Glad to see you here.")

@cli.command()
@click.argument('numbers', nargs=-1, type=int)
def add(numbers):
    """Adds numbers together."""
    result = sum(numbers)
    click.echo(f"The sum is: {result}")

if __name__ == '__main__':
    cli()
Python

Here’s what changed:

  • @click.group(): Groups multiple commands.
  • @cli.command(): Registers a new command under the cli group.
  • nargs=-1: Let the add command accept multiple arguments (like a list).

Run it:

python app.py greet
Bash

Or:

python app.py add 5 10 15
Bash

Math. Done. Fast. 💪

#5 Packaging Your CLI Tool Like a Pro

What if you want to run your CLI without typing python app.py every time? Enter setuptools. Create a setup.py file:

from setuptools import setup

setup(
    name='my_cli_tool',
    version='0.1',
    py_modules=['app'],
    install_requires=[
        'click',
    ],
    entry_points='''
        [console_scripts]
        mycli=app:cli
    ''',
)
Python

Now install your tool locally:

pip install --editable .
Bash

You can now run your python CLI tool with:

mycli greet
Bash

Mind-blowing, right? 🤯

Tips and Gotchas

  • Debugging: If your CLI crashes, don’t panic. Add --help to your commands to see what’s wrong.
  • Error messages: Use click.UsageError to display user-friendly error messages.
  • Keep it simple: Start small. Your first CLI doesn’t need to save the world, at least in the beginning.
  • Testing: Get into the habit of testing your code. It might seem like a hassle at first, but it saves you so much trouble in the long run. I learned this the hard way, believe me.
  • Documentation: Even for small tools, good documentation is key. A simple README file explaining what your tool does and how to use it can be a lifesaver.

Final Words

So there you have it, a beginner’s guide on how to building Python CLI Tool. We started with a simple greeting, moved on to a basic area calculator, and even touched on optional arguments and help messages. Not too shabby, right? I hope this guide has been helpful and you’re now itching to build your own CLI tools. Trust me, once you start, you won’t stop. It’s addictive, in a good way.

Go ahead and experiment, and don’t be afraid to break things. That’s how we learn, after all. And hey, if you get stuck, there’s a whole community of Python folks out there ready to help. Happy 🐍 coding! 🚀

Python CLI Tool FAQs

What’s the easiest way to parse command-line arguments in Python?

Use the built-in argparse module for simple cases. It’s part of Python’s standard library and handles common argument parsing needs (flags, help messages) without installing anything. For more complex CLI apps, libraries like Click or Typer provide additional features (like subcommands and better UX).

How do I make my Python CLI tool executable system-wide?

You can package it and install it. In your setup configuration, define an entry point (console script). After pip install-ing your package (or using pipx), your tool can be run from any location by its name (e.g. mytool). This involves creating a setup.py or pyproject.toml with the appropriate console_scripts entry.

Which is better for CLIs, Click or argparse?

They serve different needs. argparse is simple and comes with Python – great for basic utilities. Click (and frameworks like Typer built on it) offer more developer-friendly features: declarative command definitions, nested subcommands, automatic help, etc.

How can I distribute my CLI tool to others?

The main ways are publishing it to PyPI (so others can pip install it) or sharing the script directly. To publish, you’d package the tool (with a setup file or pyproject) and use tools like twine to upload to PyPI. Alternatively, for team use, you might just share the Python script or use a tool like pipx to help others install it in isolation.

How do I add colors or fancy output to my Python CLI?

You can use libraries like Rich or Colorama to add colored text, progress bars, tables, and more to your CLI output. These can improve user experience by making the console output easier to read or more interactive. For example, Rich can format tracebacks and create attractive help messages easily.

Rana Ahsan

Rana Ahsan is a seasoned software engineer and technology leader specialized in distributed systems and software architecture. With a Master’s in Software Engineering from Concordia University, his experience spans leading scalable architecture at Coursera and TopHat, contributing to open-source projects. This blog, CodeSamplez.com, showcases his passion for sharing practical insights on programming and distributed systems concepts and help educate others. Github | X | LinkedIn

Recent Posts

Service Workers in React: Framework Integration Guide

Learn how to integrate service workers in React, Next.js, Vue, and Angular with practical code examples and production-ready implementations for modern web applications.

2 weeks ago

Service Worker Caching Strategies: Performance & Offline Apps

Master the essential service worker caching strategies that transform web performance. Learn Cache-First, Network-First, and Stale-While-Revalidate patterns with practical examples that'll make your apps blazingly…

3 weeks ago

Service Worker Lifecycle: Complete Guide for FE Developers

Master the intricate dance of service worker states and events that power modern PWAs. From registration through installation, activation, and termination, understanding the lifecycle unlocks…

4 weeks ago

This website uses cookies.