If path is symlink to another path
Asked Answered
S

2

3

Is there a way in Python to check whether or not a file is a symlink to another specific file? For example, if /home/user/x symlinks to /home/user/z, but /home/user/y links somewhere else:

>>>print(isLink("/home/user/x", "/home/user/z"))
True
>>>print(isLink("/home/user/y", "/home/user/z"))
False
>>>print(isLink("/home/user/z", "/home/user/z"))
False

(/home/user/z is the original file, not a symlink)

Scraggy answered 26/7, 2013 at 19:23 Comment(0)
H
4
import os
def isLink(a, b):
    return os.path.islink(a) and os.path.realpath(a) == os.path.realpath(b)

Note that this resolves the second argument to a real path. So it will return True if a and b are both symlinks, as long as they both point to the same real path. If you don't want b to be resolved to a real path, then change

os.path.realpath(a) == os.path.realpath(b)

to

os.path.realpath(a) == os.path.abspath(b)

Now if a points to b, and b points to c, and you want isLink(a, b) to still be True, then you'll want to use os.readlink(a) instead of os.path.realpath(a):

def isLink(a, b):
    return os.path.islink(a) and os.path.abspath(os.readlink(a)) == os.path.abspath(b)

os.readlink(a) evaluates to b, the next link that a points to, whereas os.path.realpath(a) evaluates to c, the final path that a points to.


For example,

In [129]: !touch z

In [130]: !ln -s z x

In [131]: !touch w

In [132]: !ln -s w y

In [138]: isLink('x', 'z')
Out[138]: True

In [139]: isLink('y', 'z')
Out[139]: False

In [140]: isLink('z', 'z')
Out[140]: False
Haphazard answered 26/7, 2013 at 19:26 Comment(1)
And if you want to find out what the symlink points to, use os.path.realpath().Administer
H
1

This will do it.

os.path.realpath(path)

Here are the docs.

Hopper answered 26/7, 2013 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.