[Python-ideas] Symlink chain resolver module

Guido van Rossum guido at python.org
Tue Dec 4 20:06:03 CET 2007


Isn't this pretty close to os.path.realpath()?

On Dec 4, 2007 10:46 AM, Giampaolo Rodola' <gnewsg at gmail.com> wrote:
> 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)
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-ideas mailing list