summaryrefslogtreecommitdiff
path: root/Lib/posixpath.py
diff options
context:
space:
mode:
authorGuido van Rossum <guido@python.org>2001-09-17 15:16:09 +0000
committerGuido van Rossum <guido@python.org>2001-09-17 15:16:09 +0000
commita5ad73efb6b08c9e6d3726adfe25bf6ec0fd3850 (patch)
tree23e8dbd0263e4f546b63cb235a674243c759834e /Lib/posixpath.py
parent1f8a18bb1a3ee9459c1d19569af5427d4d6bd835 (diff)
downloadcpython-a5ad73efb6b08c9e6d3726adfe25bf6ec0fd3850.tar.gz
SF patch #461781 by Chris Lawrence: os.path.realpath - Resolve symlinks:
Once upon a time, I put together a little function that tries to find the canonical filename for a given pathname on POSIX. I've finally gotten around to turning it into a proper patch with documentation. On non-POSIX, I made it an alias for 'abspath', as that's the behavior on POSIX when no symlinks are encountered in the path. Example: >>> os.path.realpath('/usr/bin/X11/X') '/usr/X11R6/bin/X'
Diffstat (limited to 'Lib/posixpath.py')
-rw-r--r--Lib/posixpath.py21
1 files changed, 21 insertions, 0 deletions
diff --git a/Lib/posixpath.py b/Lib/posixpath.py
index 6bf40f8336..0f6b6a76db 100644
--- a/Lib/posixpath.py
+++ b/Lib/posixpath.py
@@ -379,3 +379,24 @@ def abspath(path):
if not isabs(path):
path = join(os.getcwd(), path)
return normpath(path)
+
+
+# Return a canonical path (i.e. the absolute location of a file on the
+# filesystem).
+
+def realpath(filename):
+ """Return the canonical path of the specified filename, eliminating any
+symbolic links encountered in the path."""
+ filename = abspath(filename)
+
+ bits = ['/'] + filename.split('/')[1:]
+ for i in range(2, len(bits)+1):
+ component = join(*bits[0:i])
+ if islink(component):
+ resolved = os.readlink(component)
+ (dir, file) = split(component)
+ resolved = normpath(join(dir, resolved))
+ newpath = join(*([resolved] + bits[i:]))
+ return realpath(newpath)
+
+ return filename