Check if a symlink is broken or circular

Giampaolo Rodola' gnewsg at gmail.com
Sat Dec 1 08:53:53 EST 2007


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?



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
        # circular link
        # "Too many levels of symlinks"
        elif err.errno == errno.ELOOP:
            return 2
        # something else occurred,
        # assume it as invalid anyway
        else:
            return 3
    return 0




More information about the Python-list mailing list