A script that makes an absolute path when a directory is specified with a symbolic link in the middle of the path.
followlnk.py
#!/usr/bin/env python
import os
import sys
import os.path
def follow_link(path):
path = os.path.abspath(path)
path_fragments = []
current = ""
while True:
path, child = os.path.split(path)
if child == '':
current = path # /
break
path_fragments.insert(0, child)
while path_fragments:
current = follow_child(current, path_fragments[0])
path_fragments = path_fragments[1:]
print(current)
def follow_child(current, child):
result = os.path.join(current, child)
if not os.path.islink(result):
return result
link = os.readlink(result)
if os.path.isabs(link):
return link
return os.path.abspath(os.path.join(current, link))
if __name__ == "__main__":
if len(sys.argv) > 1:
follow_link(sys.argv[1])
else:
print("%s [directory]" % sys.argv[0])
sys.exit(1)
It's a discarded script, so it's appropriate, but all you have to do is break down the path first and then go down the directory, checking for symlinks in order from the top. Since I haven't checked for errors, I may die if a directory that doesn't exist appears on the way.
$ followlink.py ./test/symdir/subdir #symdir is a symbolic link to realdir in the same location
/Users/home/shibukawa/develop/test/realdir/subdir
Recommended Posts