Check if a symlink is broken or circular

"Martin v. Löwis" martin at v.loewis.de
Fri Nov 30 18:10:03 EST 2007


> 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



More information about the Python-list mailing list