import os import os.path def splitpath(path): "returns list of all path components" L = [path] while True: path = L.pop(0) if not path: return L elif path == os.path.sep: return [path] + L else: L = list(os.path.split(path)) + L def realpath(path): current_dir = [] L = splitpath(os.path.abspath(path)) while len(L): #print(L) filename = L.pop(0) #print('filename', filename) if filename == '.': continue elif filename == '..': current_dir.pop() else: current_dir.append(filename) cwd = os.path.sep.join(current_dir) #print("cwd", cwd) if os.path.islink(cwd): tmp = os.readlink(cwd) if os.path.isabs(tmp): current_dir = splitpath(tmp) else: L = splitpath(tmp) + L current_dir.pop() return os.path.join(*current_dir) import sys path = 'zlink' path = sys.argv[1] os.system("readlink -f %s" % path) print("py ", os.path.realpath(path)) print("=> ", realpath(path))