lpugoy

resolve_symlinks.py

Jun 4th, 2013
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. import os
  2. import sys
  3.  
  4. def readlinkabs(l):
  5.   """
  6.  Return an absolute path for the destination
  7.  of a symlink - by: Greg Smith and Chris Laskey
  8.  http://notemagnet.blogspot.com/2009/09/following-symlinks-in-python.html
  9.  """
  10.   assert (os.path.islink(l))
  11.   p = os.path.normpath(os.readlink(l))
  12.   if os.path.isabs(p):
  13.     if os.path.islink(p):
  14.       # print 'symlink to symlink'
  15.       return readlinkabs(p)
  16.     else:
  17.       return p
  18.   else:
  19.     a = os.path.join(os.path.dirname(l), p)
  20.     if os.path.islink(a):
  21.       # print 'relative symlink: %s' % a
  22.       return readlinkabs(a)
  23.     else:
  24.       return a
  25.  
  26. def walk(path):
  27.   for name in os.listdir(path):
  28.     full_path = os.path.abspath(os.path.join(path, name))
  29.     if os.path.islink(full_path):
  30.       print '%s is a symlink; resolving...' % full_path
  31.       try:
  32.         target = readlinkabs(full_path)
  33.         print '%s links to %s' % (full_path, target)
  34.       except RuntimeError:
  35.         print '%s is recursive' % full_path
  36.     elif os.path.isdir(full_path):
  37.       walk(full_path)
  38.  
  39. if __name__ == '__main__':
  40.   walk(sys.argv[1])
Advertisement
Add Comment
Please, Sign In to add comment