If path is symlink to another path

妖精的绣舞 提交于 2019-12-23 22:40:32

问题


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)


回答1:


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



回答2:


This will do it.

os.path.realpath(path)

Here are the docs.



来源:https://stackoverflow.com/questions/17889368/if-path-is-symlink-to-another-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!