How to get symlink target in Python?

社会主义新天地 提交于 2019-11-30 17:12:05

The problem with os.readlink() is it will only resolve 1 step of the link. We can have a situation where A links to another link B, and B link is dangling.

$ ln -s /tmp/example/notexist /tmp/example/B
$ ln -s /tmp/example/B /tmp/example/A
$ ls -l /tmp/example
A -> /tmp/example/B
B -> /tmp/example/notexist

Now in Python, os.readlink gives you the first target.

>>> import os
>>> os.readlink('A')
'/tmp/example/B'

But in most situations I assume we are interested in the resolved path. So pathlib can help here:

>>> from pathlib import Path
>>> Path('A').resolve()
PosixPath('/tmp/example/notexist')

For older Python versions:

>>> os.path.realpath('A')
'/tmp/example/notexist'
Armin Rigo

You need to look at os.readlink().

To determine if a directory entry is a symlink use this:

os.path.islink(path)

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

AChampion

To determine if a link is broken, you can, os.walk and test os.path.exists(path) which will return False for a broken link. You can then use os.path.realpath(path) to find out what the link is supposed to be pointing to.
Something like (untested):

for root, dirs, files in os.walk('<path>'):
    for file in files:
         f = os.join(root, file)
         if os.path.islink(f) and not os.path.exists(f):
             print("Broken: {} -> {}".format(f, os.path.realpath(f)))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!