2

I am trying to remove a set of directories, excluding those that are in used and symlinked to elsewhere.

What is the most effective way to determine if a given directory is symlinked to?

I've tried os.stat(dir).mt_nlink, but it returns 3 even for directories I want to remove.

EDIT:

By symlinked to I mean this directory is a target of some symlink.

satoru
  • 31,822
  • 31
  • 91
  • 141
  • possible duplicate of [Check if file is symlink in python](http://stackoverflow.com/questions/11068419/check-if-file-is-symlink-in-python) – alko Dec 06 '13 at 09:14
  • @alko not that one but may be this one [Is there a way to check if there are symbolic links pointing to a directory?](http://stackoverflow.com/questions/100170/is-there-a-way-to-check-if-there-are-symbolic-links-pointing-to-a-directory) –  Dec 06 '13 at 09:48

3 Answers3

5

There is no easy way to determine if someone else has made a link to a given "hard" directory. You can only check if a given directory is a symlink to another directory.

This means that you need to traverse your entire directory structure, look for symlinks, and then check if they point to the directory in question.

A symlink is a special file which points to another file/directory, somewhere in your directory structure. Symlinks can point to other filesystems as well. Creating a symlink does not change the inode of the destination file/folder (as opposed to hard links), so you can't tell by looking at the target, only at the link itself.

micromoses
  • 6,747
  • 2
  • 20
  • 29
2

Use os.path.islink(path).

Straight from the docs:

Return True if path refers to a directory entry that is a symbolic link. Always False if symbolic links are not supported.

yamafontes
  • 5,552
  • 1
  • 18
  • 18
0

Use os.path.islink.

You can also test if a path is a broken link using os.path.lexists (a file is a broken link iff it lexists() and not exists()).

shx2
  • 61,779
  • 13
  • 130
  • 153
  • If you already know a path is a symlink, you don't need to call `lexists` to see if it's broken - `not exists(link)` is sufficient. – lvc Dec 06 '13 at 09:23