How to Build a Command-Line Tool in Python

Turn a throwaway Python script into a real command-line tool. This guide builds csvstat, a CSV summariser, with argparse: a planned interface, clean error handling, proper exit codes, pip packaging and tests.

Written by Projectech10 min readPublished
For B.E./B.Tech Computer Science and IT students who write Python scripts and want to turn them into proper command-line tools their teammates can actually use Topics: Python, argparse, pip, CSV, CLI
Technical illustration of a command-line tool in Python: a terminal window showing a clean csvstat command and its summary output, with a small Python file and a CSV spreadsheet feeding into it.
Illustration generated for this guide.
In this guide

Every Python student has a folder of scripts that only run one way: python script.py, fingers crossed, with the input file name hard-coded inside. That works until a teammate needs to run it, a reviewer asks for a different input, or you need it again three months later and cannot remember what it does. The fix is to turn the script into a real command-line tool: named arguments, a --help screen, proper error messages and a command you can run from anywhere.

This guide builds one from scratch. You will write a small tool called csvstat that summarises a CSV file — row count, columns, missing values — using argparse from the standard library, structure it so it can be installed with pip, and package it so teammates install it with one command. No third-party libraries are needed for the core tool.

What makes a script a tool

A script is a file you run. A tool is a program with a contract: it accepts arguments, validates them, does one job, reports errors clearly, and exits with a code that tells the caller whether it worked. The difference is small in code and large in practice — a tool can be used by someone who has never read its source, chained into other commands, and run from a scheduled job.

The anatomy is always the same: parse the arguments, validate the inputs, do the work, print the result, exit with 0 on success and a non-zero code on failure. argparse handles the first step and gives you --help for free. The rest is structure and discipline, which this guide covers in the order you would actually write it.

Step 1: Plan the interface before writing code

Decide the interface on paper first. For csvstat, the interface is one positional argument — the CSV file — and two options: --column to summarise a single column, and --json to print machine-readable output. A usage line follows directly: csvstat data.csv, csvstat data.csv --column age, csvstat data.csv --json.

Keep the interface narrow. A tool that does one thing well beats a tool with twelve flags that nobody remembers. If you catch yourself adding a flag for a case that will happen once, make it a separate small tool instead. Note the interface in the README as you design it, not after the code is finished — the README is the contract, and writing it first stops scope creep.

Step 2: Parse arguments with argparse

argparse is in the standard library, so there is nothing to install. You describe the arguments, and it builds the parser, the --help screen, the type conversion and the error messages:

import argparse

def build_parser():
    parser = argparse.ArgumentParser(
        prog="csvstat",
        description="Summarise a CSV file: row count, columns and missing values.",
    )
    parser.add_argument("file", help="Path to the CSV file to summarise")
    parser.add_argument("--column", help="Summarise one column in detail")
    parser.add_argument("--json", action="store_true",
                        help="Print the summary as JSON")
    return parser

Run csvstat --help and argparse prints a usage screen with every argument and its description — that screen is also your documentation, so write the help strings as if a stranger will read them. A missing required argument produces a clear error and exit code 2 without you writing any of that logic. Type conversion is built in too: type=int on an argument rejects non-numeric input with a readable message.

Step 3: Structure the code so it can be tested

The classic student mistake is putting all the logic at the top level of the script, which makes it untestable and unimportable. Split the tool into three parts: a main() function that parses arguments and coordinates, small functions that do the work, and the standard entry guard:

import csv
import json
import sys
from collections import Counter

def summarise(path):
    with open(path, newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    if not rows:
        return {"rows": 0, "columns": [], "missing": {}}
    columns = list(rows[0].keys())
    missing = {c: sum(1 for r in rows if not r[c].strip()) for c in columns}
    return {"rows": len(rows), "columns": columns, "missing": missing}

def main(argv=None):
    args = build_parser().parse_args(argv)
    try:
        summary = summarise(args.file)
    except FileNotFoundError:
        print(f"csvstat: no such file: {args.file}", file=sys.stderr)
        return 2
    except UnicodeDecodeError:
        print("csvstat: file is not valid UTF-8 text", file=sys.stderr)
        return 2
    if args.json:
        print(json.dumps(summary, indent=2))
    else:
        print(f"Rows: {summary['rows']}")
        print("Columns: " + ", ".join(summary["columns"]))
        for col, count in summary["missing"].items():
            print(f"  {col}: {count} missing")
    return 0

if __name__ == "__main__":
    sys.exit(main())

Notice what this structure buys you. summarise() can be imported and tested without running the argument parser. main() takes an optional argv list, so a test can call main(["sample.csv"]) directly. Errors print to stderr, not stdout, so piping the output to a file or another program still works. And every failure path returns a non-zero exit code, which is how scripts and scheduled jobs detect that something went wrong.

Step 4: Handle files and errors like a tool, not a script

A tool meets files it did not expect: a missing file, a file with the wrong encoding, a CSV with no header row, a directory passed where a file was expected. Each of those needs a one-line error on stderr and a non-zero exit, not a traceback. Catch the specific exceptions — FileNotFoundError, PermissionError, UnicodeDecodeError, csv.Error — and give each a message that says what went wrong and what the user should do.

Never print a bare traceback to a user. A traceback is a debugging aid for the developer, and it tells a user nothing useful. Log it if you need it for your own debugging, behind a --verbose flag, and print the short message by default. This one habit is the largest visible difference between a student script and a finished tool.

Step 5: Make it installable with a console script

A tool that only runs as python csvstat.py from its own folder is still a script. Packaging it properly means anyone can install it and run csvstat from any directory. The modern way is a pyproject.toml file in the project root:

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[project]
name = "csvstat"
version = "0.1.0"
description = "Summarise a CSV file from the command line"
requires-python = ">=3.9"

[project.scripts]
csvstat = "csvstat:main"

[tool.setuptools]
py-modules = ["csvstat"]

The [project.scripts] section is the key line: it tells pip to create a csvstat command that calls your main() function. Install it in editable mode while developing — pip install -e . — and every save is immediately live, with no reinstall step. Your teammates install it the same way from the repository, and the command works from any directory on their machine.

Step 6: Test the tool the way a user would

Test from a clean directory, not from the project folder where everything happens to work. Create a small sample CSV with known properties — a known row count, a column with two missing values — and check the output against what you expect. Test the failure paths: a missing file, a non-CSV file, --column with a column that does not exist, and no arguments at all. Each should produce a clear message and a non-zero exit code.

Write at least one automated test for summarise(), using the standard library unittest or pytest. A test that builds a tiny CSV in a temporary file, calls summarise(), and checks the row count and missing-value counts takes ten lines and catches regressions the moment you change the parsing logic. Test the argument parser too: build_parser().parse_args(["data.csv", "--json"]) should return the values you expect. These tests are also evidence for a reviewer that the tool was verified, not just written.

Common mistakes

  • Hard-coding file names and values inside the script. Every input that might change belongs in an argument, with a sensible default where one exists.
  • Printing errors to stdout. Output is for results; diagnostics go to stderr, or piping and redirection break.
  • Exiting 0 on failure. A script that fails silently with exit code 0 will pass every automated check while producing nothing.
  • No --help text, or help text written for the author. The help screen is the manual. Write it for a stranger.
  • All logic at module top level. Nothing is importable, nothing is testable, and importing the file runs the whole program.
  • Catching every exception with a bare except. It hides real bugs. Catch the specific errors you expect and let unexpected ones surface during development.
  • Skipping packaging. If installing the tool takes more than one command, nobody will install it — including you, three months later.

Frequently asked questions

argparse or Click for a student project?
argparse. It is in the standard library, it covers everything a small tool needs, and it teaches the concepts — parsers, positional versus optional arguments, subcommands — that transfer directly to Click later. Reach for Click when you need nested subcommands, like git has, or rich prompting and colours.

How do I add subcommands, like git commit and git push?
argparse supports subparsers: one parser per subcommand, each with its own arguments. Add them when the tool genuinely has two or more distinct jobs. Do not add subcommands to a tool with one job — a single flat interface is easier to learn and to document.

Can I distribute the tool without publishing to PyPI?
Yes. Teammates can install it straight from a Git repository with pip install git+https://github.com/yourname/csvstat.git, or from a zip of the project folder. Publishing to PyPI is only needed when strangers should be able to pip install csvstat by name.

Should the tool read from stdin?
Support it when it makes sense: if no file argument is given, read CSV from sys.stdin. That makes the tool composable — cat data.csv | csvstat — which is the Unix habit that turns a small tool into a building block. Keep it optional, and document which mode is the default.

How do I handle large files?
Do not load the whole file into memory. Stream it row by row with csv.DictReader and accumulate only the counts you need. The summarise() function above reads all rows into a list, which is fine for a classroom CSV but is the first thing to change when the file grows.

What exit codes should I use?
Zero means success. Two is the conventional code argparse uses for bad arguments, so use 2 for your own usage errors too. One is the general-purpose failure code. Anything beyond that is your own scheme — document it in the README if you use it.

Limitations

This guide covers a single-file tool built on the standard library. It does not cover interactive prompts, coloured output, progress bars, configuration files, or plugin systems — those belong in a second version, once the basic tool is installed and used. A command-line tool is also the wrong interface when the audience is non-technical: if the users cannot open a terminal, the same logic belongs behind a small web form instead.

Get your project tooling built with Projectech

If your project needs command-line tools, data-processing scripts or automation around it — and you want them built, tested and documented properly — message Projectech on WhatsApp with what the tool should do, what it reads and writes, and your deadline. You will get a quotation stating the scope, price and delivery timeline: https://wa.me/918275719193

More project guides

More in Computer / IT