Python Projects · Lesson 148 of 149

Python Project Command-line Tool with argparse

What you will build

  • A command-line tool with three subcommands
  • Using argparse, pathlib, hashlib, Counter, defaultdict
  • Exit codes and error messages on standard error
  • A main(argv) function and tests
  • An efficient duplicate finder

1. The idea

foldertool looks inside a folder and answers three questions:

python foldertool.py summary    FOLDER          how many files, how big, of which types?
python foldertool.py big        FOLDER --top 5  which are the biggest files?
python foldertool.py duplicates FOLDER          which files have identical content?

Real tools are used from the terminal, from scripts, and by other programs, so they must behave well: clear help, clear errors, and meaningful exit codes (0 for success, non-zero for failure, lesson 17.7).

2. The design

Piece Job
human_size(n) 1536 → 1.5 KB
list_files(folder) every file below the folder, sorted
file_hash(path) SHA-256 fingerprint of a file's content, read in chunks (lesson 15.8)
summary, biggest, duplicates return data or lines, never print
build_parser() the argparse setup (lesson 17.8)
main(argv=None) parse, run the command, print, and return the exit code

As in the earlier projects, the work functions return values; only main prints. And main takes argv so tests can call it directly (lesson 17.8).

Finding duplicates efficiently. Reading every file completely to compute fingerprints is slow for big folders. But two files can only be identical if they have the same size. So the tool first groups files by size (cheap: just a stat call) and hashes only files that share a size with another file. Then files with the same hash are duplicates. This is the standard approach.

3. The code

foldertool.py:

"""foldertool: look inside a folder from the command line.

    python foldertool.py summary  FOLDER
    python foldertool.py big      FOLDER [--top 5]
    python foldertool.py duplicates FOLDER
"""

import argparse
import hashlib
import sys
from collections import Counter, defaultdict
from pathlib import Path


def human_size(size):
    """1536 -> '1.5 KB'."""
    for unit in ("B", "KB", "MB", "GB"):
        if size < 1024 or unit == "GB":
            return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
        size /= 1024


def list_files(folder):
    return sorted(p for p in Path(folder).rglob("*") if p.is_file())


def file_hash(path, chunk_size=65536):
    digest = hashlib.sha256()
    with open(path, "rb") as f:
        while chunk := f.read(chunk_size):
            digest.update(chunk)
    return digest.hexdigest()


def summary(folder):
    files = list_files(folder)
    sizes = [p.stat().st_size for p in files]
    kinds = Counter(p.suffix.lower() or "(none)" for p in files)
    lines = [f"{len(files)} files, {human_size(sum(sizes))} in total"]
    for kind, count in kinds.most_common():
        lines.append(f"  {kind:<8}{count:>4}")
    return lines


def biggest(folder, top):
    files = sorted(list_files(folder), key=lambda p: p.stat().st_size, reverse=True)
    root = Path(folder)
    return [f"{human_size(p.stat().st_size):>9}  {p.relative_to(root).as_posix()}" for p in files[:top]]


def duplicates(folder):
    by_size = defaultdict(list)
    for p in list_files(folder):
        by_size[p.stat().st_size].append(p)
    by_hash = defaultdict(list)
    for same_size in by_size.values():
        if len(same_size) > 1:                      # only hash files that could match
            for p in same_size:
                by_hash[file_hash(p)].append(p)
    root = Path(folder)
    groups = [sorted(p.relative_to(root).as_posix() for p in paths)
              for paths in by_hash.values() if len(paths) > 1]
    return sorted(groups)


def build_parser():
    parser = argparse.ArgumentParser(prog="foldertool", description="Look inside a folder.")
    sub = parser.add_subparsers(dest="command", required=True)
    for name, text in [("summary", "count files by type"),
                       ("big", "list the largest files"),
                       ("duplicates", "find files with identical content")]:
        p = sub.add_parser(name, help=text)
        p.add_argument("folder", type=Path, help="the folder to look at")
        if name == "big":
            p.add_argument("--top", type=int, default=5, help="how many files to list (default 5)")
    return parser


def main(argv=None):
    args = build_parser().parse_args(argv)
    if not args.folder.is_dir():
        print(f"foldertool: not a folder: {args.folder}", file=sys.stderr)
        return 2
    if args.command == "summary":
        print("\n".join(summary(args.folder)))
    elif args.command == "big":
        if args.top < 1:
            print("foldertool: --top must be at least 1", file=sys.stderr)
            return 2
        print("\n".join(biggest(args.folder, args.top)) or "(no files)")
    else:
        groups = duplicates(args.folder)
        if not groups:
            print("no duplicates found")
        for number, group in enumerate(groups, start=1):
            print(f"group {number}: " + ", ".join(group))
    return 0


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

Points to notice:

  • human_size divides by 1024 until the number is small. The for ... in with return inside is a compact loop (lesson 6.2); GB is the last unit.
  • rglob("*") with is_file() finds files at every depth (lesson 15.5). sorted makes the output repeatable.
  • Counter(...).most_common() counts types; p.suffix.lower() or "(none)" handles files without an extension (lessons 17.3 and 3.3).
  • The subparsers give each command its own arguments. type=Path converts the folder text to a Path; required=True makes a missing command an error.
  • main returns codes: 0 normally, 2 for a bad folder or bad option (the same code argparse uses for its own errors). Errors go to sys.stderr.
  • sys.exit(main()) passes the code to the operating system. In a script you can check it ($? or %ERRORLEVEL%).
  • The duplicate groups are sorted so the output is stable.
Quick check: why does `duplicates` group files by size before hashing them?

Files of different sizes cannot be identical, so only files that share a size need to be read and hashed. That saves a lot of time on big folders.

4. Running it

A test folder was created with seven files: two identical text files (a.txt and notes/copy_of_a.txt), a different text file, three JPEG-named binary files (two identical, one not) and a file with no extension. The demo calls main with an argument list and shows the output, with the folder path replaced by FOLDER:

$ foldertool summary FOLDER
7 files, 32.7 KB in total
  .txt       3
  .jpg       3
  (none)     1
[exit code 0]
$ foldertool big FOLDER --top 3
  10.0 KB  photos/x.jpg
  10.0 KB  photos/y.jpg
  10.0 KB  photos/z.jpg
[exit code 0]
$ foldertool duplicates FOLDER
group 1: a.txt, notes/copy_of_a.txt
group 2: photos/x.jpg, photos/y.jpg
[exit code 0]

(The total size depends on the system: on Windows, text files written with write_text use two bytes for each line ending, which made the text files larger than the same files on Linux or macOS would be. The three images have identical sizes, so the order of ties follows the sorted file order.) Now the errors:

$ foldertool big FOLDER --top 0
foldertool: --top must be at least 1
[exit code 2]
$ foldertool summary FOLDER/nothing_here
foldertool: not a folder: FOLDER/nothing_here
[exit code 2]
$ foldertool big FOLDER --top many
usage: foldertool big [-h] [--top TOP] folder
foldertool big: error: argument --top: invalid int value: 'many'
[exit code 2]
$ foldertool sizes FOLDER
usage: foldertool [-h] {summary,big,duplicates} ...
foldertool: error: argument command: invalid choice: 'sizes' (choose from summary, big, duplicates)
[exit code 2]

And the help that argparse wrote for us:

usage: foldertool [-h] {summary,big,duplicates} ...

Look inside a folder.

positional arguments:
  {summary,big,duplicates}
    summary             count files by type
    big                 list the largest files
    duplicates          find files with identical content

options:
  -h, --help            show this help message and exit

and for one command (foldertool big --help):

usage: foldertool big [-h] [--top TOP] folder

positional arguments:
  folder      the folder to look at

options:
  -h, --help  show this help message and exit
  --top TOP   how many files to list (default 5)

human_size gave 0 B, 999 B, 1.0 KB, 1.5 KB, 5.0 MB and 3.0 GB for 0, 999, 1024, 1536, 5 MiB and 3 GiB.

5. Tests

The tests build a small folder with known content in a temporary directory, call main with argument lists, and capture the output and errors:

import contextlib
import io
import tempfile
import unittest
from pathlib import Path

import foldertool


def run(*argv):
    out, err = io.StringIO(), io.StringIO()
    with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
        try:
            code = foldertool.main([str(a) for a in argv])
        except SystemExit as exit_:
            code = exit_.code
    return code, out.getvalue(), err.getvalue()


class TestHumanSize(unittest.TestCase):
    def test_units(self):
        self.assertEqual(foldertool.human_size(0), "0 B")
        self.assertEqual(foldertool.human_size(1023), "1023 B")
        self.assertEqual(foldertool.human_size(1024), "1.0 KB")
        self.assertEqual(foldertool.human_size(1536), "1.5 KB")
        self.assertEqual(foldertool.human_size(3 * 1024**3), "3.0 GB")


class TestCommands(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.root = Path(self.tmp.name)
        (self.root / "sub").mkdir()
        (self.root / "one.txt").write_bytes(b"x" * 100)
        (self.root / "sub" / "two.txt").write_bytes(b"x" * 100)
        (self.root / "sub" / "three.bin").write_bytes(b"y" * 100)
        (self.root / "sub" / "big.bin").write_bytes(b"z" * 5000)

    def tearDown(self):
        self.tmp.cleanup()

    def test_summary_counts_by_type(self):
        code, out, _ = run("summary", self.root)
        self.assertEqual(code, 0)
        self.assertIn("4 files", out)
        self.assertIn(".txt", out)

    def test_big_lists_largest_first(self):
        code, out, _ = run("big", self.root, "--top", 2)
        lines = out.strip().splitlines()
        self.assertEqual(len(lines), 2)
        self.assertTrue(lines[0].endswith("sub/big.bin"))

    def test_duplicates_compares_content_not_names(self):
        _, out, _ = run("duplicates", self.root)
        self.assertIn("one.txt, sub/two.txt", out)
        self.assertNotIn("three.bin", out)

    def test_no_duplicates_message(self):
        (self.root / "one.txt").write_bytes(b"different")
        _, out, _ = run("duplicates", self.root)
        self.assertEqual(out.strip(), "no duplicates found")

    def test_errors_use_exit_code_2_and_stderr(self):
        code, out, err = run("summary", self.root / "missing")
        self.assertEqual((code, out), (2, ""))
        self.assertIn("not a folder", err)
        code, _, err = run("big", self.root, "--top", 0)
        self.assertEqual(code, 2)
        self.assertEqual(run("unknown", self.root)[0], 2)
        self.assertEqual(run()[0], 2)


if __name__ == "__main__":
    unittest.main()

Result: Ran 6 tests ... OK. Notice: argparse calls sys.exit(2) on bad usage, so the test helper catches SystemExit and reads its code. Writing bytes with write_bytes keeps the test file sizes the same on every system, which write_text would not.

6. Ideas to extend it

  1. --min-size for duplicates, to ignore tiny files (in bytes, or with a parser for 10KB).
  2. --delete (carefully!) with a confirmation prompt, or a --dry-run that only says what would happen. Never delete without asking.
  3. --ext .jpg filter for summary and big.
  4. JSON output with --json for use by other programs (lesson 15.7).
  5. Progress and logging with the logging module and a --verbose flag counted by action="count" (lesson 17.9).
  6. Speed: hash files with a thread pool (hashing releases the GIL, lesson 20.6).
  7. Install it as a real command with pyproject.toml and [project.scripts] (lesson 19.5), so you can type foldertool summary ..
  8. Ignore folders such as .git and __pycache__.

Worked example: the checklist of a good command-line tool

Quality How foldertool achieves it
clear usage argparse descriptions and help= strings produce --help automatically
helpful errors messages start with the tool name, go to standard error, and say what is wrong
exit codes 0 success, 2 usage error, via sys.exit(main())
no surprises read-only: it never changes or deletes anything
testable main(argv) returns a code; work functions return data
efficient duplicates: compare sizes first, hash only candidates, read in chunks
repeatable output sorted files, sorted groups
portable pathlib, as_posix() for display, bytes for tests

Skills used: argparse (17.8), pathlib and folders (15.4, 15.5), binary files and hashing (15.8), collections (17.3), functions (chapter 11), testing (chapter 18), project layout (19.5). The folders, file names and sizes in the demo are made up for the lesson.

Common mistakes

  • Printing from the work functions, so nothing can be tested.
  • Ignoring exit codes (always returning 0, even on failure).
  • Printing errors to standard output.
  • Hashing every file, even those with a unique size.
  • Reading a whole big file into memory to hash it.
  • Parsing sys.argv by hand.
  • Dangerous defaults: a tool that deletes without --dry-run or confirmation.
  • Not handling a missing folder or bad option values.

Key takeaways

  • A good command-line tool has clear --help, helpful errors on standard error, and meaningful exit codes.
  • argparse subparsers give commands their own arguments; type=Path and type=int convert for you.
  • Keep work in functions that return data; keep printing and exit codes in main(argv).
  • To find duplicate files, group by size first, then hash only the candidates, reading in chunks.
  • Test the tool by calling main with argument lists and capturing output; catch SystemExit for argparse errors.

Practice

1. What does sys.exit(main()) do?

Show answer

It ends the program with the exit code that main returned, so scripts can tell success (0) from failure.

2. Why must two files have the same size before they can be duplicates?

Show answer

Identical content means identical length, so files of different sizes cannot match; comparing sizes avoids needless hashing.

3. How would you add a --ext option to big?

Show answer

Add p.add_argument("--ext") for that command and filter in biggest: [p for p in files if p.suffix.lower() == ext.lower()].

4. Why are error messages printed to sys.stderr?

Show answer

They stay visible when the normal output is redirected to a file or piped to another program, and do not pollute that output.

5. How can a test call the tool without a real terminal?

Show answer

Call main(["summary", str(folder)]) and capture stdout and stderr with contextlib.redirect_stdout and redirect_stderr.

6. How would you make foldertool a command you can type anywhere?

Show answer

Package it with a pyproject.toml that has [project.scripts] foldertool = "foldertool:main", and install it with pip install -e . (lesson 19.5).