[Python-ideas] Symlink chain resolver module
Giampaolo Rodola'
gnewsg at gmail.com
Tue Dec 4 19:46:15 CET 2007
Hi there,
I thought it would have been good sharing this code I used in a
project of mine.
I thought it could eventually look good incorporated in Python stdlib
through os or os.path modules.
Otherwise I'm merely offering it as a community service to anyone who
might be interested.
-- Giampaolo
#!/usr/bin/env python
# linkchainresolver.py
import os, sys, errno
def resolvelinkchain(path):
"""Resolve a chain of symbolic links by returning the absolute
path
name of the final target.
Raise os.error exception in case of circular link.
Do not raise exception if the symlink is broken (pointing to a
non-existent path).
Return a normalized absolutized version of the pathname if it is
not a symbolic link.
Examples:
>>> resolvelinkchain('validlink')
/abstarget
>>> resolvelinkchain('brokenlink') # resolved anyway
/abstarget
>>> resolvelinkchain('circularlink')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "module.py", line 19, in resolvelinkchain
os.stat(path)
OSError: [Errno 40] Too many levels of symbolic links: '3'
>>>
"""
try:
os.stat(path)
except os.error, err:
# do not raise exception in case of broken symlink;
# we want to know the final target anyway
if err.errno == errno.ENOENT:
pass
else:
raise
if not os.path.isabs(path):
basedir = os.path.dirname(os.path.abspath(path))
else:
basedir = os.path.dirname(path)
p = path
while os.path.islink(p):
p = os.readlink(p)
if not os.path.isabs(p):
p = os.path.join(basedir, p)
basedir = os.path.dirname(p)
return os.path.join(basedir, p)
More information about the Python-ideas
mailing list