使用Python查找损坏的符号链接 [英] Find broken symlinks with Python

查看:139
本文介绍了使用Python查找损坏的符号链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在损坏的symlink上调用os.stat(),python会抛出OSError异常.这对于找到它们很有用.但是,还有其他一些原因可能导致os.stat()抛出类似的异常.在Linux下,是否有更精确的方法来使用Python检测损坏的symlinks?

If I call os.stat() on a broken symlink, python throws an OSError exception. This makes it useful for finding them. However, there are a few other reasons that os.stat() might throw a similar exception. Is there a more precise way of detecting broken symlinks with Python under Linux?

推荐答案

Python常见的说法是,请求宽恕比允许许可容易.尽管我不喜欢现实生活中的这种说法,但它确实适用于许多情况.通常,您要避免将两个系统调用链接到同一文件的代码,因为您永远不知道代码中两次调用之间的文件会发生什么情况.

A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code.

一个典型的错误是写类似的内容:

if os.path.exists(path):
    os.unlink(path)

如果第二次调用(os.unlink)在if测试后因其他原因将其删除,引发Exception并停止执行其余函数,则可能会失败. (您可能会认为这在现实生活中不会发生,但是上周我们只是在我们的代码库中钓出了另一个类似的错误-正是这种错误使一些程序员挠头并声称"Heisenbug"最近几个月)

The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months)

因此,在您的特定情况下,我可能会这样做:

So, in your particular case, I would probably do:

try:
    os.stat(path)
except OSError, e:
    if e.errno == errno.ENOENT:
        print 'path %s does not exist or is a broken symlink' % path
    else:
        raise e

这里的烦人之处在于stat对于不存在的符号链接和损坏的符号链接返回相同的错误代码.

The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink.

所以,我想您别无选择,只能打破原子性,并做类似的事情

So, I guess you have no choice than to break the atomicity, and do something like

if not os.path.exists(os.readlink(path)):
    print 'path %s is a broken symlink' % path

这篇关于使用Python查找损坏的符号链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆