如果我打电话 os.stat() 在破碎的 symlink, python 抛出一个 OSError 例外。这对于寻找它们非常有用。然而,还有其他一些原因 os.stat() 可能会抛出类似的异常。有没有更精确的方法来检测损坏 symlinks Linux下用Python?

有帮助吗?

解决方案

Python 的一个常见说法是请求原谅比请求许可更容易。虽然我在现实生活中不喜欢这种说法,但它确实适用于很多情况。通常,您希望避免在同一文件上链接两个系统调用的代码,因为您永远不知道代码中的两个调用之间的文件会发生什么。

一个典型的错误是这样写:

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

如果在 if 测试之后有其他东西删除了第二个调用 (os.unlink),则第二个调用 (os.unlink) 可能会失败,引发异常,并停止执行函数的其余部分。(你可能认为这在现实生活中不会发生,但我们上周刚刚从我们的代码库中发现了另一个类似的错误 - 这种错误让一些程序员摸不着头脑,并声称“Heisenbug”是最近几个月)

所以,在你的具体情况下,我可能会这样做:

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 对于不存在的符号链接和损坏的符号链接返回相同的错误代码。

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

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

其他提示

os.lstat() 可能会有帮助。如果 lstat() 成功而 stat() 失败,那么它可能是一个损坏的链接。

这不是原子的,但它有效。

os.path.islink(filename) and not os.path.exists(filename)

确实是由 实时FM(阅读精彩的手册)我们看到

os.path.exists(路径)

如果路径引用现有路径,则返回 True。对于损坏的符号链接返回 False。

它还说:

在某些平台上,如果未授予对请求的文件执行 os.stat() 的权限,则此函数可能会返回 False,即使路径实际存在。

所以如果你担心权限问题,你应该添加其他条款。

我可以提到不用 python 来测试硬链接吗?/bin/test 具有 FILE1 -ef FILE2 条件,当文件共享 inode 时该条件为 true。

因此,像 find . -type f -exec test \{} -ef /path/to/file \; -print 适用于特定文件的硬链接测试。

这让我开始阅读 man test 以及提到的 -L-h 它们都适用于一个文件,如果该文件是符号链接,则返回 true,但这并不能告诉您目标是否丢失。

我确实发现了 head -0 FILE1 将返回退出代码 0 如果文件可以打开并且 1 如果不能,则在指向常规文件的符号链接的情况下,可以测试目标是否可以读取。

操作系统路径

您可以尝试使用 realpath() 来获取符号链接指向的内容,然后尝试使用 is file. 确定它是否是有效文件。

(我现在无法尝试,所以你必须尝试一下,看看你会得到什么)

我不是 python 爱好者,但它看起来像 os.readlink()?我在 perl 中使用的逻辑是使用 readlink() 查找目标,并使用 stat() 测试目标是否存在。

编辑:我敲出了一些演示阅读链接的 Perl。我相信 Perl 的 stat 和 readlink 以及 python 的 os.stat() 和 os.readlink() 都是系统调用的包装器,因此这应该可以合理地翻译为概念验证代码:

wembley 0 /home/jj33/swap > cat p
my $f = shift;

while (my $l = readlink($f)) {
  print "$f -> $l\n";
  $f = $l;
}

if (!-e $f) {
  print "$f doesn't exist\n";
}
wembley 0 /home/jj33/swap > ls -l | grep ^l
lrwxrwxrwx    1 jj33  users          17 Aug 21 14:30 link -> non-existant-file
lrwxrwxrwx    1 root     users          31 Oct 10  2007 mm -> ../systems/mm/20071009-rewrite//
lrwxrwxrwx    1 jj33  users           2 Aug 21 14:34 mmm -> mm/
wembley 0 /home/jj33/swap > perl p mm
mm -> ../systems/mm/20071009-rewrite/
wembley 0 /home/jj33/swap > perl p mmm
mmm -> mm
mm -> ../systems/mm/20071009-rewrite/
wembley 0 /home/jj33/swap > perl p link
link -> non-existant-file
non-existant-file doesn't exist
wembley 0 /home/jj33/swap >

我有一个类似的问题:如何捕获损坏的符号链接,即使它们出现在某些父目录中?我还想记录所有这些(在处理相当大量文件的应用程序中),但没有太多重复。

这是我的想法,包括单元测试。

文件工具.py:

import os
from functools import lru_cache
import logging

logger = logging.getLogger(__name__)

@lru_cache(maxsize=2000)
def check_broken_link(filename):
    """
    Check for broken symlinks, either at the file level, or in the
    hierarchy of parent dirs.
    If it finds a broken link, an ERROR message is logged.
    The function is cached, so that the same error messages are not repeated.

    Args:
        filename: file to check

    Returns:
        True if the file (or one of its parents) is a broken symlink.
        False otherwise (i.e. either it exists or not, but no element
        on its path is a broken link).

    """
    if os.path.isfile(filename) or os.path.isdir(filename):
        return False
    if os.path.islink(filename):
        # there is a symlink, but it is dead (pointing nowhere)
        link = os.readlink(filename)
        logger.error('broken symlink: {} -> {}'.format(filename, link))
        return True
    # ok, we have either:
    #   1. a filename that simply doesn't exist (but the containing dir
           does exist), or
    #   2. a broken link in some parent dir
    parent = os.path.dirname(filename)
    if parent == filename:
        # reached root
        return False
    return check_broken_link(parent)

单元测试:

import logging
import shutil
import tempfile
import os

import unittest
from ..util import fileutil


class TestFile(unittest.TestCase):

    def _mkdir(self, path, create=True):
        d = os.path.join(self.test_dir, path)
        if create:
            os.makedirs(d, exist_ok=True)
        return d

    def _mkfile(self, path, create=True):
        f = os.path.join(self.test_dir, path)
        if create:
            d = os.path.dirname(f)
            os.makedirs(d, exist_ok=True)
            with open(f, mode='w') as fp:
                fp.write('hello')
        return f

    def _mklink(self, target, path):
        f = os.path.join(self.test_dir, path)
        d = os.path.dirname(f)
        os.makedirs(d, exist_ok=True)
        os.symlink(target, f)
        return f

    def setUp(self):
        # reset the lru_cache of check_broken_link
        fileutil.check_broken_link.cache_clear()

        # create a temporary directory for our tests
        self.test_dir = tempfile.mkdtemp()

        # create a small tree of dirs, files, and symlinks
        self._mkfile('a/b/c/foo.txt')
        self._mklink('b', 'a/x')
        self._mklink('b/c/foo.txt', 'a/f')
        self._mklink('../..', 'a/b/c/y')
        self._mklink('not_exist.txt', 'a/b/c/bad_link.txt')
        bad_path = self._mkfile('a/XXX/c/foo.txt', create=False)
        self._mklink(bad_path, 'a/b/c/bad_path.txt')
        self._mklink('not_a_dir', 'a/bad_dir')

    def tearDown(self):
        # Remove the directory after the test
        shutil.rmtree(self.test_dir)

    def catch_check_broken_link(self, expected_errors, expected_result, path):
        filename = self._mkfile(path, create=False)
        with self.assertLogs(level='ERROR') as cm:
            result = fileutil.check_broken_link(filename)
            logging.critical('nothing')  # trick: emit one extra message, so the with assertLogs block doesn't fail
        error_logs = [r for r in cm.records if r.levelname is 'ERROR']
        actual_errors = len(error_logs)
        self.assertEqual(expected_result, result, msg=path)
        self.assertEqual(expected_errors, actual_errors, msg=path)

    def test_check_broken_link_exists(self):
        self.catch_check_broken_link(0, False, 'a/b/c/foo.txt')
        self.catch_check_broken_link(0, False, 'a/x/c/foo.txt')
        self.catch_check_broken_link(0, False, 'a/f')
        self.catch_check_broken_link(0, False, 'a/b/c/y/b/c/y/b/c/foo.txt')

    def test_check_broken_link_notfound(self):
        self.catch_check_broken_link(0, False, 'a/b/c/not_found.txt')

    def test_check_broken_link_badlink(self):
        self.catch_check_broken_link(1, True, 'a/b/c/bad_link.txt')
        self.catch_check_broken_link(0, True, 'a/b/c/bad_link.txt')

    def test_check_broken_link_badpath(self):
        self.catch_check_broken_link(1, True, 'a/b/c/bad_path.txt')
        self.catch_check_broken_link(0, True, 'a/b/c/bad_path.txt')

    def test_check_broken_link_badparent(self):
        self.catch_check_broken_link(1, True, 'a/bad_dir/c/foo.txt')
        self.catch_check_broken_link(0, True, 'a/bad_dir/c/foo.txt')
        # bad link, but shouldn't log a new error:
        self.catch_check_broken_link(0, True, 'a/bad_dir/c')
        # bad link, but shouldn't log a new error:
        self.catch_check_broken_link(0, True, 'a/bad_dir')

if __name__ == '__main__':
    unittest.main()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top