如果路径符号链接到另一个路径 [英] If path is symlink to another path

查看:173
本文介绍了如果路径符号链接到另一个路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法在Python中检查文件是否是另一个特定文件的符号链接?例如,如果 / home / user / x 符号链接到 / home / user / z ,但<$ c $

 >>>打印(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


$ b

解决方案

  import os 
def isLink(a,b):
(b)

请注意,这会将第二个参数解析为真实路径。所以如果 a b 都是符号链接,那么它将返回True,只要它们都指向相同的实际路径。如果您不希望将 b 解析为实际路径,请更改

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



  os.path.realpath(a)== os.path.abspath code> 

现在如果 a 指向 b b 指向 c ,并且您希望 isLink ,b)仍然是真的,那么你会希望使用 os.readlink(a)而不是 os (b):

$ $ $ $ b返回os.path.islink(a)和os.path.abspath(os.readlink(a))== os.path.abspath(b)

os.readlink(a)的计算结果为 b a 指向,而 os.path.realpath(a)评估至 c 指向
$ b




例如,

  In [129]:!touch z 

In [130]:!ln -szx

In在[132]中:!ln -swy

在[138]中:isLink('x','z')
[138]:True

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

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


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)

解决方案

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

这篇关于如果路径符号链接到另一个路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆