# ===================================================================
# From: www.linux-magazine.com/Issues/2022/261/
# Tutorial-Detecting-Broken-Links
#
# First, the program creates and validates a directory listing.
# In case of an error, the walk() function terminates here.
# Then the code checks each entry in the directory to see if it is
# a file (line 11), a directory, or a link. The routine skips files.
# For directories, the walk() function is called recursively, again
# with the directory name as parameter.
#
# For a link, however, the readlink() function from the os module
# in line finds the target. If it is empty, it is a broken link,
# and the function returns an error message to that effect. After
# checking all the entries in the directory, the function returns
# to the call point.
# ===================================================================
# This creates a symbolic link dst to src
# import os
# src = '/usr/bin/python'
# dst = '/tmp/python'
# os.symlink(src, dst)
# print('symlink created')
# ===================================================================
import os,sys
# ---- walk a directory tree
def walk(top):
try:
entries = os.listdir(top)
except os.error:
return
for name in entries:
path = os.path.join(top, name)
if os.path.isfile(path):
pass
if os.path.isdir(path):
walk(path)
if os.path.islink(path):
destination = os.readlink(path)
if not os.path.exists(path):
print(f'broken link: from {path} points to {destination}')
return
# ---- main
startingDir = sys.argv[1]
walk(startingDir)