[Python-ideas] Symlink chain resolver module
Giampaolo Rodola'
gnewsg at gmail.com
Tue Dec 4 20:25:32 CET 2007
On 4 Dic, 20:06, "Guido van Rossum" <gu... at python.org> wrote:
> Isn't this pretty close to os.path.realpath()?
>
> On Dec 4, 2007 10:46 AM, Giampaolo Rodola' <gne... 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-id... at python.org
> >http://mail.python.org/mailman/listinfo/python-ideas
>
> --
> --Guido van Rossum (home page:http://www.python.org/~guido/)
> _______________________________________________
> Python-ideas mailing list
> Python-id... at python.orghttp://mail.python.org/mailman/listinfo/python-ideas- Nascondi testo tra virgolette -
>
> - Mostra testo tra virgolette -
Are you trying to tell me that I've lost the whole evening when such a
thing was already available in os.path? :-)
Wait a moment. I'm going to check what os.path.realpath() does.
More information about the Python-ideas
mailing list