os.path.realpath() on POSIX

Chris Lawrence quango at watervalley.net
Mon Jun 7 08:58:15 CEST 1999


This patch implements a realpath() function (cfr GNU libc) that gives
the canonical location of a file on the filesystem, resolving any
symlinks in the middle.

For example, /usr/bin/X11/xterm is often actually
/usr/X11R6/bin/xterm, even though xterm itself is not a symbolic link
(the link is usually /usr/bin/X11 -> /usr/X11R6/bin or ../../X11R6/bin).

This sort of thing is useful when you're trying to track down what
package includes a certain file, etc.

This patch also gives abspath() a docstring.

[os.path.realpath() should probably act like os.path.abspath() on most
non-POSIX systems.]

--- /usr/lib/python1.5/posixpath.py	Fri May 21 10:26:23 1999
+++ posixpath.py	Mon Jun  7 01:48:16 1999
@@ -371,6 +371,28 @@
 
 # Return an absolute path.
 def abspath(path):
+    """Return an absolute path.  If the path does not start with a /, assume
+it is relative to os.getcwd()."""
     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."""
+    import string
+    filename = abspath(filename)
+
+    bits = ['/'] + string.split(filename, '/')[1:]
+    for i in range(2, len(bits)+1):
+        component = apply(join, bits[0:i])
+        if islink(component):
+            resolved = os.readlink(component)
+            (dir, file) = split(component)
+            resolved = normpath(join(dir, resolved))
+            newpath = apply(join, [resolved] + bits[i:])
+            return realpath(newpath)
+
+    return filename


Chris
-- 
=============================================================================
|          Chris Lawrence         |       Get your Debian 2.1 CD-ROMs       |
|     <quango at watervalley.net>    |        http://www.lordsutch.com/        |
|                                 |                                         |
|     Grad Student, Pol. Sci.     |     Do you want your bank to snoop?     |
|    University of Mississippi    |    http://www.defendyourprivacy.com/    |
=============================================================================




More information about the Python-list mailing list