Walk a Directory Tree Without Hanging on Circular Symlinks

os.walk(root, followlinks=True) is the standard way to recurse through a directory tree in Python while respecting symlinks. It is also the standard way to accidentally create an infinite loop. If any symlink in your tree points back to an ancestor—or even to a sibling that eventually cycles—you get a process that walks forever, building ever-longer path strings and consuming memory until you Ctrl-C it or the kernel OOM-kills it.

I hit this in a log-collection script for a home server. A backup job had created /var/log/app/backup → /var/log, and my walker started enumerating the same files under deeper and deeper prefixes: /var/log/app/backup/var/log/app/backup/var/log/.... The script did not crash. It simply never finished. I had to kill -9 it from another terminal.

The fix is small but specific, and it hinges on one function: os.path.realpath(). Track the canonical form of every directory you visit in a set; when a canonical path shows up a second time, you have found a loop — report it, prune that branch, and keep listing everything else.

Verified terminal output of walksafe.py — real test runs in a clean, network-isolated container.

What goes wrong when you follow links

With followlinks=False (the default), os.walk treats symlinked directories as files: it lists them but never descends into them. That is safe, but it silently skips the contents of any linked directory, which is usually not what a backup or indexing script wants.

Turn on followlinks=True and the walker descends into symlinked directories like any other. The problem is that os.walk has no memory of where it has been. A cycle — a link pointing back at an ancestor — means the iterator keeps producing the same directory under deeper and deeper prefixes: the root, then the root via the link, then the root via the link twice, and so on. Each iteration is cheap, which is exactly why the failure mode is so nasty: there is no error, no traceback, no warning. Just a process whose runtime grows without bound while it re-lists the same files forever.

Shell tools fare no better. POSIX leaves the behavior of find -L on symlink loops unspecified; GNU find detects some loops and prints a "File system loop detected" warning before skipping them, but other implementations simply keep walking. If your pipeline mixes find output with Python, you cannot assume either side is safe — the walker itself has to carry the cycle check.

The design goal for the script below: list every real file in the tree exactly once, and report every loop it finds on stderr — without ever hanging.

Why realpath does the work

The canonical form

Every path in a filesystem has exactly one canonical form once you resolve all symlinks, .. segments, and redundant slashes. os.path.realpath("/var/log/app/backup/var/log") returns /var/log, because the symlink chain collapses to the true location. That means if you track every canonical path you have already visited in a set, any subsequent directory whose realpath is already in that set is a cycle: you have been there before through a different link path. Stop going deeper.

The check is a hash-set lookup per directory, so it adds nothing measurable to the walk itself. And because realpath resolves the entire target chain, a multi-hop loop — x -> y -> z -> x — is caught the same way as a one-hop self-loop: every hop eventually re-enters an already-seen canonical path.

Pruning with dirnames[:] = []

The other half of the trick is how os.walk lets you prune branches. The iterator yields a three-tuple: (dirpath, dirnames, filenames). If you mutate dirnames in place—specifically, if you clear it with the slice assignment dirnames[:] = []—the walker will not descend into any subdirectory from that point forward. It is the documented mechanism for skipping branches. You do not need a custom generator or a hand-rolled recursive function; you just tell the standard library "do not go further here."

Note that it must be slice assignment, not dirnames = []. Rebinding the local name leaves the walker's own list untouched and descends anyway — a classic bug that only shows up when a loop is actually present in the tree.

The script

#!/usr/bin/env python3
"""Walk a directory tree, detecting circular symlinks without hanging."""
import os, sys

def main():
    if len(sys.argv) < 2:
        print("usage: walksafe.py <root_dir>", file=sys.stderr)
        sys.exit(1)
    root = sys.argv[1]
    if not os.path.isdir(root):
        print(f"error: '{root}' is not a directory", file=sys.stderr)
        sys.exit(1)
    seen = set()
    loops, files = [], []
    for dirpath, dirnames, filenames in os.walk(root, followlinks=True):
        real = os.path.realpath(dirpath)
        if real in seen:
            loops.append(dirpath)
            dirnames[:] = []
            continue
        seen.add(real)
        files.extend(os.path.join(dirpath, f) for f in sorted(filenames))
    for f in files:
        print(f)
    for l in loops:
        print(f"LOOP: {l} -> {os.path.realpath(l)}", file=sys.stderr)

main()

Walk through what each section does and why it is shaped that way.

Argument handling

The argument check is two lines. If no path is given, or the path exists but is not a directory, you get a single message on stderr and a non-zero exit code. No traceback, no "did you mean" suggestions. Just the error and out. This matters when the script runs from cron: you want a clean failure in your mail log, not a 40-line stack dump.

The seen set and loop reporting

seen is a set of canonical paths. It starts empty. On each iteration of the os.walk loop, you compute real = os.path.realpath(dirpath). If that value is already in seen, you have reached a directory through a different symlink path than the one that got you here the first time. You record it in the loops list for later reporting, clear dirnames so the walker will not descend further into that branch, and continue to the next directory the iterator produces.

If the realpath is new, you add it to seen and extend the files list with every filename in that directory, joined to its full path. I sort filenames before extending so the output order is deterministic regardless of the order the filesystem returns directory entries. Without the sort, two runs on the same tree could produce different line orderings if the underlying inode table shifted, which makes diffing your output between runs annoying and error-prone.

Keeping stdout clean

After the walk completes, you print all collected file paths to stdout, one per line. Then you print each detected loop to stderr in the form LOOP: <path> -> <realpath>, so the cycle information does not pollute your file list if you are piping stdout into another tool like xargs or a build system. The script still exits zero when the walk succeeds — even with loops found — because it did its job: it listed the tree and told you where the cycles are.

Verification

The harness builds six fixtures in /tmp/testdata inside a clean, network-isolated Ubuntu container and runs the script against each one. It passed on the first verification attempt. Here is what each test does, with the real output.

Simple tree

A plain two-level tree with no symlinks at all — the sanity check that the walker lists everything:

=== RUN: python3 /work/walksafe.py /tmp/testdata/simple
/tmp/testdata/simple/a.txt
/tmp/testdata/simple/sub/b.txt
PASS: simple tree

The core bug: a circular symlink

A directory real inside the root contains one file and a symlink loop pointing back at the root itself. This is the exact shape of the failure that hangs naive walkers — and it is the test the whole post exists for. The walker must report the loop and still list the real file:

=== RUN: python3 /work/walksafe.py /tmp/testdata/cycle
LOOP: /tmp/testdata/cycle/real/loop -> /tmp/testdata/cycle
/tmp/testdata/cycle/real/file.txt
PASS: circular symlink detected, real file still listed

The LOOP: line on stderr shows the link path and where it actually resolves. The file is listed exactly once — the cycle is cut before the walker can re-enter.

Paths with spaces

A fixture whose directory names contain spaces, to make sure quoting survives:

=== RUN: python3 /work/walksafe.py '/tmp/testdata/dir with spaces'
/tmp/testdata/dir with spaces/my file.txt
/tmp/testdata/dir with spaces/sub dir/nested file.txt
PASS: paths with spaces

Bad input, two ways

Missing argument and non-existent path both need a clean non-zero exit, not a traceback:

=== RUN: python3 /work/walksafe.py
usage: walksafe.py <root_dir>
PASS: missing arg handled with non-zero exit
=== RUN: python3 /work/walksafe.py /tmp/testdata/does_not_exist
error: '/tmp/testdata/does_not_exist' is not a directory
PASS: non-existent path handled with non-zero exit

Stress: 200 directories with a buried cycle

The final fixture creates 200 sibling directories d1 through d200, each containing one file, plus a circular symlink at d50/back pointing back to the tree root — a loop buried in the middle of the walk. The harness asserts that at least 200 file lines are printed and that the loop is reported:

=== RUN: python3 /work/walksafe.py /tmp/testdata/stress
LOOP: /tmp/testdata/stress/d50/back -> /tmp/testdata/stress
/tmp/testdata/stress/d200/f.txt
...
/tmp/testdata/stress/d1/f.txt
PASS: stress (200 dirs + buried cycle)

The ... elides the 198 middle lines, which are the remaining dNNN/f.txt paths in descending order. All six tests pass — the harness ends with:

ALL TESTS PASSED

No hangs, no tracebacks, no infinite loops. The script exited cleanly on every fixture.

How to use it

Save the script as walksafe.py and make it executable:

chmod +x walksafe.py
./walksafe.py /var/log

Pipe stdout into wc -l to count files without printing them all:

./walksafe.py /home/user/projects | wc -l

If you need the loop warnings but do not want them cluttering your terminal, redirect stderr to a file:

./walksafe.py /mnt/backup 2> loops.txt

In cron, capture both streams so a discovered loop is visible in the log without breaking the file list:

./walksafe.py /var/log > files.txt 2> loops.txt

The script is a single file with no dependencies beyond the Python standard library. Drop it next to any cron job, backup script, or indexing pipeline that walks a tree you do not fully control, and you will not be the person staring at top six hours later wondering why a Python process has been running since Tuesday.


Luke Keam
Spot a bug or want a custom utility built? I'd love to hear from you. Get in touch
Luke Keam | techgeek.biz