blob: b01c3cb90850cb3fe1461409f3260d2f08a9ab51 [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""Common operations on Posix pathnames.
2
3Instead of importing this module directly, import os and refer to
4this module as os.path. The "os.path" name is an alias for this
5module on Posix systems; on other systems (e.g. Mac, Windows),
6os.path provides the same operations in a manner specific to that
7platform, and is an alias to another module (e.g. macpath, ntpath).
8
9Some of this can actually be useful on non-Posix systems too, e.g.
10for manipulation of the pathname component of URLs.
Guido van Rossum346f7af1997-12-05 19:04:51 +000011"""
Guido van Rossumc6360141990-10-13 19:23:40 +000012
Guido van Rossumd3876d31996-07-23 03:47:28 +000013import os
Guido van Rossum40d93041990-10-21 16:17:34 +000014import stat
Martin v. Löwis05c075d2007-03-07 11:04:33 +000015import genericpath
Benjamin Peterson0893a0a2008-05-09 00:27:01 +000016import warnings
Jack Diederich7b604642006-08-26 18:42:06 +000017from genericpath import *
Guido van Rossumc6360141990-10-13 19:23:40 +000018
Skip Montanaroc62c81e2001-02-12 02:00:42 +000019__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
20 "basename","dirname","commonprefix","getsize","getmtime",
Georg Brandlf0de6a12005-08-22 18:02:59 +000021 "getatime","getctime","islink","exists","lexists","isdir","isfile",
22 "ismount","walk","expanduser","expandvars","normpath","abspath",
Neal Norwitz61cdac62003-01-03 18:01:57 +000023 "samefile","sameopenfile","samestat",
Skip Montanaro117910d2003-02-14 19:35:31 +000024 "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
Collin Winter6f187742007-03-16 22:16:08 +000025 "devnull","realpath","supports_unicode_filenames","relpath"]
Guido van Rossumc6360141990-10-13 19:23:40 +000026
Skip Montanaro117910d2003-02-14 19:35:31 +000027# strings representing various path-related bits and pieces
28curdir = '.'
29pardir = '..'
30extsep = '.'
31sep = '/'
32pathsep = ':'
33defpath = ':/bin:/usr/bin'
34altsep = None
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000035devnull = '/dev/null'
Skip Montanaro117910d2003-02-14 19:35:31 +000036
Guido van Rossum7ac48781992-01-14 18:29:32 +000037# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
38# On MS-DOS this may also turn slashes into backslashes; however, other
39# normalizations (such as optimizing '../' away) are not allowed
40# (another function should be defined to do that).
41
42def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000043 """Normalize case of pathname. Has no effect under Posix"""
44 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000045
46
Jeremy Hyltona05e2932000-06-28 14:48:01 +000047# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000048# Trivial in Posix, harder on the Mac or MS-DOS.
49
50def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000051 """Test whether a path is absolute"""
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000052 return s.startswith('/')
Guido van Rossum7ac48781992-01-14 18:29:32 +000053
54
Barry Warsaw384d2491997-02-18 21:53:25 +000055# Join pathnames.
56# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000057# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000058
Barry Warsaw384d2491997-02-18 21:53:25 +000059def join(a, *p):
Georg Brandlda5f16a2007-08-23 21:27:57 +000060 """Join two or more pathname components, inserting '/' as needed.
61 If any component is an absolute path, all previous path components
62 will be discarded."""
Guido van Rossum346f7af1997-12-05 19:04:51 +000063 path = a
64 for b in p:
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000065 if b.startswith('/'):
Guido van Rossum346f7af1997-12-05 19:04:51 +000066 path = b
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000067 elif path == '' or path.endswith('/'):
68 path += b
Guido van Rossum346f7af1997-12-05 19:04:51 +000069 else:
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000070 path += '/' + b
Guido van Rossum346f7af1997-12-05 19:04:51 +000071 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000072
73
Guido van Rossum26847381992-03-31 18:54:35 +000074# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000075# rest). If the path ends in '/', tail will be empty. If there is no
76# '/' in the path, head will be empty.
77# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000078
Guido van Rossumc6360141990-10-13 19:23:40 +000079def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +000080 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +000081 everything after the final slash. Either part may be empty."""
Fred Drake22fb8392000-09-28 15:04:39 +000082 i = p.rfind('/') + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +000083 head, tail = p[:i], p[i:]
Fred Drake8152d322000-12-12 23:20:45 +000084 if head and head != '/'*len(head):
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000085 head = head.rstrip('/')
Guido van Rossum346f7af1997-12-05 19:04:51 +000086 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +000087
88
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000089# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +000090# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000091# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +000092# It is always true that root + ext == p.
93
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000094def splitext(p):
Martin v. Löwis05c075d2007-03-07 11:04:33 +000095 return genericpath._splitext(p, sep, altsep, extsep)
96splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000097
Guido van Rossum221df241995-08-07 20:17:55 +000098# Split a pathname into a drive specification and the rest of the
99# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
100
101def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000102 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000103 empty."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000104 return '', p
Guido van Rossum221df241995-08-07 20:17:55 +0000105
106
Georg Brandl65ad0432006-10-12 13:08:16 +0000107# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000108
Guido van Rossumc6360141990-10-13 19:23:40 +0000109def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000110 """Returns the final component of a pathname"""
Georg Brandl65ad0432006-10-12 13:08:16 +0000111 i = p.rfind('/') + 1
112 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000113
114
Georg Brandl65ad0432006-10-12 13:08:16 +0000115# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000116
117def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000118 """Returns the directory component of a pathname"""
Georg Brandl65ad0432006-10-12 13:08:16 +0000119 i = p.rfind('/') + 1
120 head = p[:i]
121 if head and head != '/'*len(head):
122 head = head.rstrip('/')
123 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000124
125
Guido van Rossum7ac48781992-01-14 18:29:32 +0000126# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000127# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000128
129def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000130 """Test whether a path is a symbolic link"""
131 try:
132 st = os.lstat(path)
133 except (os.error, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000134 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000135 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000136
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000137# Being true for dangling symbolic links is also useful.
138
139def lexists(path):
140 """Test whether a path exists. Returns True for broken symbolic links"""
141 try:
Georg Brandl84fedf72010-02-06 22:59:15 +0000142 os.lstat(path)
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000143 except os.error:
144 return False
145 return True
146
147
Guido van Rossumd3778f91991-11-12 15:37:40 +0000148# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000149
Guido van Rossumd3778f91991-11-12 15:37:40 +0000150def samefile(f1, f2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000151 """Test whether two pathnames reference the same actual file"""
152 s1 = os.stat(f1)
153 s2 = os.stat(f2)
154 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000155
156
157# Are two open files really referencing the same file?
158# (Not necessarily the same file descriptor!)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000159
Guido van Rossumd3778f91991-11-12 15:37:40 +0000160def sameopenfile(fp1, fp2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000161 """Test whether two open file objects reference the same file"""
162 s1 = os.fstat(fp1)
163 s2 = os.fstat(fp2)
164 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000165
166
167# Are two stat buffers (obtained from stat, fstat or lstat)
168# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000169
Guido van Rossumd3778f91991-11-12 15:37:40 +0000170def samestat(s1, s2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000171 """Test whether two stat buffers reference the same file"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000172 return s1.st_ino == s2.st_ino and \
173 s1.st_dev == s2.st_dev
Guido van Rossumc6360141990-10-13 19:23:40 +0000174
175
176# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000177# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000178
Guido van Rossumc6360141990-10-13 19:23:40 +0000179def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000180 """Test whether a path is a mount point"""
Georg Brandl78e69572010-08-01 18:52:52 +0000181 if islink(path):
182 # A symlink can never be a mount point
183 return False
Guido van Rossum346f7af1997-12-05 19:04:51 +0000184 try:
Christian Heimes06875612008-01-04 13:21:07 +0000185 s1 = os.lstat(path)
186 s2 = os.lstat(join(path, '..'))
Guido van Rossum346f7af1997-12-05 19:04:51 +0000187 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000188 return False # It doesn't exist -- so not a mount point :-)
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000189 dev1 = s1.st_dev
190 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000191 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000192 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000193 ino1 = s1.st_ino
194 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000195 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000196 return True # path/.. is the same i-node as path
197 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000198
199
200# Directory tree walk.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000201# For each directory under top (including top itself, but excluding
202# '.' and '..'), func(arg, dirname, filenames) is called, where
203# dirname is the name of the directory and filenames is the list
Guido van Rossum346f7af1997-12-05 19:04:51 +0000204# of files (and subdirectories etc.) in the directory.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000205# The func may modify the filenames list, to implement a filter,
Guido van Rossumc6360141990-10-13 19:23:40 +0000206# or to impose a different order of visiting.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000207
Guido van Rossumc6360141990-10-13 19:23:40 +0000208def walk(top, func, arg):
Tim Peterscf5e6a42001-10-10 04:16:20 +0000209 """Directory tree walk with callback function.
210
211 For each directory in the directory tree rooted at top (including top
212 itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
213 dirname is the name of the directory, and fnames a list of the names of
214 the files and subdirectories in dirname (excluding '.' and '..'). func
215 may modify the fnames list in-place (e.g. via del or slice assignment),
216 and walk will only recurse into the subdirectories whose names remain in
217 fnames; this can be used to implement a filter, or to impose a specific
218 order of visiting. No semantics are defined for, or required of, arg,
219 beyond that arg is always passed to func. It can be used, e.g., to pass
220 a filename pattern, or a mutable object designed to accumulate
221 statistics. Passing None for arg is common."""
Philip Jenveyd846f1d2009-05-08 02:28:39 +0000222 warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",
223 stacklevel=2)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000224 try:
225 names = os.listdir(top)
226 except os.error:
227 return
228 func(arg, top, names)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000229 for name in names:
Tim Peters2344fae2001-01-15 00:50:52 +0000230 name = join(top, name)
Guido van Rossuma490d582001-04-16 18:12:04 +0000231 try:
232 st = os.lstat(name)
233 except os.error:
234 continue
Neal Norwitzec7cf132002-06-06 18:16:14 +0000235 if stat.S_ISDIR(st.st_mode):
Tim Peters2344fae2001-01-15 00:50:52 +0000236 walk(name, func, arg)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000237
238
239# Expand paths beginning with '~' or '~user'.
240# '~' means $HOME; '~user' means that user's home directory.
241# If the path doesn't begin with '~', or if the user or $HOME is unknown,
242# the path is returned unchanged (leaving error reporting to whatever
243# function is called with the expanded path as argument).
244# See also module 'glob' for expansion of *, ? and [...] in pathnames.
245# (A function should also be defined to do full *sh-style environment
246# variable expansion.)
247
248def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000249 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000250 do nothing."""
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000251 if not path.startswith('~'):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000252 return path
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000253 i = path.find('/', 1)
254 if i < 0:
255 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000256 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000257 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000258 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000259 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000260 else:
261 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000262 else:
263 import pwd
264 try:
265 pwent = pwd.getpwnam(path[1:i])
266 except KeyError:
267 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000268 userhome = pwent.pw_dir
Georg Brandl3f0ef202009-04-05 14:48:49 +0000269 userhome = userhome.rstrip('/') or userhome
Guido van Rossum346f7af1997-12-05 19:04:51 +0000270 return userhome + path[i:]
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000271
272
273# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000274# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000275# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000276
277_varprog = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000278
279def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000280 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000281 are left unchanged."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000282 global _varprog
283 if '$' not in path:
284 return path
285 if not _varprog:
286 import re
287 _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
288 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000289 while True:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000290 m = _varprog.search(path, i)
291 if not m:
292 break
293 i, j = m.span(0)
294 name = m.group(1)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000295 if name.startswith('{') and name.endswith('}'):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000296 name = name[1:-1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000297 if name in os.environ:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000298 tail = path[j:]
299 path = path[:i] + os.environ[name]
300 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000301 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000302 else:
303 i = j
304 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000305
306
307# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
308# It should be understood that this may change the meaning of the path
309# if it contains symbolic links!
310
311def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000312 """Normalize path, eliminating double slashes, etc."""
Ezio Melottib5689de2010-01-12 03:32:05 +0000313 # Preserve unicode (if path is unicode)
314 slash, dot = (u'/', u'.') if isinstance(path, unicode) else ('/', '.')
Skip Montanaro018dfae2000-07-19 17:09:51 +0000315 if path == '':
Ezio Melottib5689de2010-01-12 03:32:05 +0000316 return dot
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000317 initial_slashes = path.startswith('/')
318 # POSIX allows one or two initial slashes, but treats three or more
319 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000320 if (initial_slashes and
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000321 path.startswith('//') and not path.startswith('///')):
322 initial_slashes = 2
Fred Drake22fb8392000-09-28 15:04:39 +0000323 comps = path.split('/')
Skip Montanaro018dfae2000-07-19 17:09:51 +0000324 new_comps = []
325 for comp in comps:
326 if comp in ('', '.'):
327 continue
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000328 if (comp != '..' or (not initial_slashes and not new_comps) or
Skip Montanaro018dfae2000-07-19 17:09:51 +0000329 (new_comps and new_comps[-1] == '..')):
330 new_comps.append(comp)
331 elif new_comps:
332 new_comps.pop()
333 comps = new_comps
Ezio Melottib5689de2010-01-12 03:32:05 +0000334 path = slash.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000335 if initial_slashes:
Ezio Melottib5689de2010-01-12 03:32:05 +0000336 path = slash*initial_slashes + path
337 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000338
339
Guido van Rossume294cf61999-01-29 18:05:18 +0000340def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000341 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000342 if not isabs(path):
Ezio Melotti4cc80ca2010-02-20 08:09:39 +0000343 if isinstance(path, unicode):
344 cwd = os.getcwdu()
345 else:
346 cwd = os.getcwd()
347 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000348 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000349
350
351# Return a canonical path (i.e. the absolute location of a file on the
352# filesystem).
353
354def realpath(filename):
355 """Return the canonical path of the specified filename, eliminating any
356symbolic links encountered in the path."""
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000357 if isabs(filename):
358 bits = ['/'] + filename.split('/')[1:]
359 else:
Georg Brandl268e61c2005-06-03 14:28:50 +0000360 bits = [''] + filename.split('/')
Tim Petersa45cacf2004-08-20 03:47:14 +0000361
Guido van Rossum83eeef42001-09-17 15:16:09 +0000362 for i in range(2, len(bits)+1):
363 component = join(*bits[0:i])
Brett Cannonf50299c2004-07-10 22:55:15 +0000364 # Resolve symbolic links.
Brett Cannondfa5d952004-07-11 19:16:21 +0000365 if islink(component):
Brett Cannonf50299c2004-07-10 22:55:15 +0000366 resolved = _resolve_link(component)
367 if resolved is None:
368 # Infinite loop -- return original component + rest of the path
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000369 return abspath(join(*([component] + bits[i:])))
Brett Cannonf50299c2004-07-10 22:55:15 +0000370 else:
371 newpath = join(*([resolved] + bits[i:]))
Tim Petersa45cacf2004-08-20 03:47:14 +0000372 return realpath(newpath)
Tim Petersb64bec32001-09-18 02:26:39 +0000373
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000374 return abspath(filename)
Tim Petersa45cacf2004-08-20 03:47:14 +0000375
Brett Cannonf50299c2004-07-10 22:55:15 +0000376
377def _resolve_link(path):
378 """Internal helper function. Takes a path and follows symlinks
Tim Peters182b5ac2004-07-18 06:16:08 +0000379 until we either arrive at something that isn't a symlink, or
Brett Cannonf50299c2004-07-10 22:55:15 +0000380 encounter a path we've seen before (meaning that there's a loop).
381 """
Benjamin Peterson1763f8a2009-01-27 03:07:53 +0000382 paths_seen = set()
Brett Cannonf50299c2004-07-10 22:55:15 +0000383 while islink(path):
Brett Cannondfa5d952004-07-11 19:16:21 +0000384 if path in paths_seen:
Brett Cannonf50299c2004-07-10 22:55:15 +0000385 # Already seen this path, so we must have a symlink loop
386 return None
Benjamin Peterson1763f8a2009-01-27 03:07:53 +0000387 paths_seen.add(path)
Brett Cannonf50299c2004-07-10 22:55:15 +0000388 # Resolve where the link points to
Brett Cannondfa5d952004-07-11 19:16:21 +0000389 resolved = os.readlink(path)
Andrew M. Kuchlingc75f1122004-08-02 14:54:16 +0000390 if not isabs(resolved):
Brett Cannonf50299c2004-07-10 22:55:15 +0000391 dir = dirname(path)
392 path = normpath(join(dir, resolved))
393 else:
394 path = normpath(resolved)
395 return path
396
Just van Rossum2d4e9882003-07-17 15:11:49 +0000397supports_unicode_filenames = False
Collin Winter6f187742007-03-16 22:16:08 +0000398
399def relpath(path, start=curdir):
400 """Return a relative version of a path"""
401
402 if not path:
403 raise ValueError("no path specified")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000404
Collin Winter6f187742007-03-16 22:16:08 +0000405 start_list = abspath(start).split(sep)
406 path_list = abspath(path).split(sep)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000407
Collin Winter6f187742007-03-16 22:16:08 +0000408 # Work out how much of the filepath is shared by start and path.
409 i = len(commonprefix([start_list, path_list]))
410
411 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Georg Brandl183a0842008-01-06 14:27:15 +0000412 if not rel_list:
413 return curdir
Collin Winter6f187742007-03-16 22:16:08 +0000414 return join(*rel_list)