Find broken symlinks with Python

后端 未结 8 1449
广开言路
广开言路 2020-12-15 05:17

If I call os.stat() on a broken symlink, python throws an OSError exception. This makes it useful for finding them. However, there are

相关标签:
8条回答
  • 2020-12-15 05:37

    This is not atomic but it works.

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

    Indeed by RTFM (reading the fantastic manual) we see

    os.path.exists(path)

    Return True if path refers to an existing path. Returns False for broken symbolic links.

    It also says:

    On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

    So if you are worried about permissions, you should add other clauses.

    0 讨论(0)
  • 2020-12-15 05:44

    I'm not a python guy but it looks like os.readlink()? The logic I would use in perl is to use readlink() to find the target and the use stat() to test to see if the target exists.

    Edit: I banged out some perl that demos readlink. I believe perl's stat and readlink and python's os.stat() and os.readlink()are both wrappers for the system calls, so this should translate reasonable well as proof of concept code:

    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 >
    
    0 讨论(0)
提交回复
热议问题