Check if a symlink is broken or circular
davisn90210 at gmail.com
davisn90210 at gmail.com
Sat Dec 1 13:28:19 EST 2007
Giampaolo Rodola' wrote:
> On 1 Dic, 00:10, "Martin v. L�wis" <mar... at v.loewis.de> wrote:
> > > I would like to know if such function would be correct for verifying
> > > if a link is broken and/or circular.
> >
> > > def isvalidlink(path):
> > > assert os.path.islink(path)
> > > try:
> > > os.stat(path)
> > > except os.error:
> > > return 1
> > > return 0
> >
> > You meant to flip the result values, right? 1 should mean that the
> > link is value, and 0 that it is not.
> >
> > Mostly. If the link is correct, but you don't have permission to stat
> > the target file, you get 0. OTOH, in that case, you have no way of
> > finding out whether the link *is* correct.
> >
> > Still, you could try to detect the errnos that indicate a problem
> > with the link itself, and pass all other errors through.
> >
> > Regards,
> > Martin
>
> Mmmm... do you mean something like this?
> Could it be ok?
>
>
I think he meant something like this (see below):
>
> import os, errno
>
> def isvalidlink(path):
> assert os.path.lexists(path)
> try:
> os.stat(path)
> except os.error, err:
> # broken link
> # "No such file or directory"
> if err.errno == errno.ENOENT:
> return 1
Right, except that it should be return 0 (or preferably return False)
unless you want inverted logic.
> # circular link
> # "Too many levels of symlinks"
> elif err.errno == errno.ELOOP:
> return 2
Change to return 1/True (inverted) or return 0/False (not inverted)
> # something else occurred,
> # assume it as invalid anyway
> else:
> return 3
Change "return 3" to "raise", so the exception gets propagated.
> return 0
Again, if you do not want the logic to be inverted, use return 1/True
instead
--Nathan Davis
More information about the Python-list
mailing list