blob: 690c70da374b660517d656ad45ae17f15da3a4bb [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
Hirokazu Yamamotoc3937f52010-09-18 05:40:44 +000014import sys
Guido van Rossum40d93041990-10-21 16:17:34 +000015import stat
Martin v. Löwis05c075d2007-03-07 11:04:33 +000016import genericpath
Benjamin Peterson0893a0a2008-05-09 00:27:01 +000017import warnings
Jack Diederich7b604642006-08-26 18:42:06 +000018from genericpath import *
Guido van Rossumc6360141990-10-13 19:23:40 +000019
Martin v. Löwised11a5d2012-05-20 10:42:17 +020020try:
21 _unicode = unicode
22except NameError:
23 # If Python is built without Unicode support, the unicode type
24 # will not exist. Fake one.
25 class _unicode(object):
26 pass
27
Skip Montanaroc62c81e2001-02-12 02:00:42 +000028__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
29 "basename","dirname","commonprefix","getsize","getmtime",
Georg Brandlf0de6a12005-08-22 18:02:59 +000030 "getatime","getctime","islink","exists","lexists","isdir","isfile",
31 "ismount","walk","expanduser","expandvars","normpath","abspath",
Neal Norwitz61cdac62003-01-03 18:01:57 +000032 "samefile","sameopenfile","samestat",
Skip Montanaro117910d2003-02-14 19:35:31 +000033 "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
Collin Winter6f187742007-03-16 22:16:08 +000034 "devnull","realpath","supports_unicode_filenames","relpath"]
Guido van Rossumc6360141990-10-13 19:23:40 +000035
Skip Montanaro117910d2003-02-14 19:35:31 +000036# strings representing various path-related bits and pieces
37curdir = '.'
38pardir = '..'
39extsep = '.'
40sep = '/'
41pathsep = ':'
42defpath = ':/bin:/usr/bin'
43altsep = None
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000044devnull = '/dev/null'
Skip Montanaro117910d2003-02-14 19:35:31 +000045
Guido van Rossum7ac48781992-01-14 18:29:32 +000046# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
47# On MS-DOS this may also turn slashes into backslashes; however, other
48# normalizations (such as optimizing '../' away) are not allowed
49# (another function should be defined to do that).
50
51def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000052 """Normalize case of pathname. Has no effect under Posix"""
53 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000054
55
Jeremy Hyltona05e2932000-06-28 14:48:01 +000056# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000057# Trivial in Posix, harder on the Mac or MS-DOS.
58
59def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000060 """Test whether a path is absolute"""
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000061 return s.startswith('/')
Guido van Rossum7ac48781992-01-14 18:29:32 +000062
63
Barry Warsaw384d2491997-02-18 21:53:25 +000064# Join pathnames.
65# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000066# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000067
Barry Warsaw384d2491997-02-18 21:53:25 +000068def join(a, *p):
Georg Brandlda5f16a2007-08-23 21:27:57 +000069 """Join two or more pathname components, inserting '/' as needed.
70 If any component is an absolute path, all previous path components
71 will be discarded."""
Guido van Rossum346f7af1997-12-05 19:04:51 +000072 path = a
73 for b in p:
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000074 if b.startswith('/'):
Guido van Rossum346f7af1997-12-05 19:04:51 +000075 path = b
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000076 elif path == '' or path.endswith('/'):
77 path += b
Guido van Rossum346f7af1997-12-05 19:04:51 +000078 else:
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000079 path += '/' + b
Guido van Rossum346f7af1997-12-05 19:04:51 +000080 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000081
82
Guido van Rossum26847381992-03-31 18:54:35 +000083# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000084# rest). If the path ends in '/', tail will be empty. If there is no
85# '/' in the path, head will be empty.
86# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000087
Guido van Rossumc6360141990-10-13 19:23:40 +000088def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +000089 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +000090 everything after the final slash. Either part may be empty."""
Fred Drake22fb8392000-09-28 15:04:39 +000091 i = p.rfind('/') + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +000092 head, tail = p[:i], p[i:]
Fred Drake8152d322000-12-12 23:20:45 +000093 if head and head != '/'*len(head):
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000094 head = head.rstrip('/')
Guido van Rossum346f7af1997-12-05 19:04:51 +000095 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +000096
97
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000098# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +000099# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000100# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000101# It is always true that root + ext == p.
102
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000103def splitext(p):
Martin v. Löwis05c075d2007-03-07 11:04:33 +0000104 return genericpath._splitext(p, sep, altsep, extsep)
105splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000106
Guido van Rossum221df241995-08-07 20:17:55 +0000107# Split a pathname into a drive specification and the rest of the
108# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
109
110def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000111 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000112 empty."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000113 return '', p
Guido van Rossum221df241995-08-07 20:17:55 +0000114
115
Georg Brandl65ad0432006-10-12 13:08:16 +0000116# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000117
Guido van Rossumc6360141990-10-13 19:23:40 +0000118def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000119 """Returns the final component of a pathname"""
Georg Brandl65ad0432006-10-12 13:08:16 +0000120 i = p.rfind('/') + 1
121 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000122
123
Georg Brandl65ad0432006-10-12 13:08:16 +0000124# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000125
126def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000127 """Returns the directory component of a pathname"""
Georg Brandl65ad0432006-10-12 13:08:16 +0000128 i = p.rfind('/') + 1
129 head = p[:i]
130 if head and head != '/'*len(head):
131 head = head.rstrip('/')
132 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000133
134
Guido van Rossum7ac48781992-01-14 18:29:32 +0000135# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000136# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000137
138def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000139 """Test whether a path is a symbolic link"""
140 try:
141 st = os.lstat(path)
142 except (os.error, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000143 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000144 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000145
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000146# Being true for dangling symbolic links is also useful.
147
148def lexists(path):
149 """Test whether a path exists. Returns True for broken symbolic links"""
150 try:
Georg Brandl84fedf72010-02-06 22:59:15 +0000151 os.lstat(path)
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000152 except os.error:
153 return False
154 return True
155
156
Guido van Rossumd3778f91991-11-12 15:37:40 +0000157# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000158
Guido van Rossumd3778f91991-11-12 15:37:40 +0000159def samefile(f1, f2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000160 """Test whether two pathnames reference the same actual file"""
161 s1 = os.stat(f1)
162 s2 = os.stat(f2)
163 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000164
165
166# Are two open files really referencing the same file?
167# (Not necessarily the same file descriptor!)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000168
Guido van Rossumd3778f91991-11-12 15:37:40 +0000169def sameopenfile(fp1, fp2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000170 """Test whether two open file objects reference the same file"""
171 s1 = os.fstat(fp1)
172 s2 = os.fstat(fp2)
173 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000174
175
176# Are two stat buffers (obtained from stat, fstat or lstat)
177# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000178
Guido van Rossumd3778f91991-11-12 15:37:40 +0000179def samestat(s1, s2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000180 """Test whether two stat buffers reference the same file"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000181 return s1.st_ino == s2.st_ino and \
182 s1.st_dev == s2.st_dev
Guido van Rossumc6360141990-10-13 19:23:40 +0000183
184
185# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000186# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000187
Guido van Rossumc6360141990-10-13 19:23:40 +0000188def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000189 """Test whether a path is a mount point"""
Georg Brandl78e69572010-08-01 18:52:52 +0000190 if islink(path):
191 # A symlink can never be a mount point
192 return False
Guido van Rossum346f7af1997-12-05 19:04:51 +0000193 try:
Christian Heimes06875612008-01-04 13:21:07 +0000194 s1 = os.lstat(path)
195 s2 = os.lstat(join(path, '..'))
Guido van Rossum346f7af1997-12-05 19:04:51 +0000196 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000197 return False # It doesn't exist -- so not a mount point :-)
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000198 dev1 = s1.st_dev
199 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000200 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000201 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000202 ino1 = s1.st_ino
203 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000204 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000205 return True # path/.. is the same i-node as path
206 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000207
208
209# Directory tree walk.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000210# For each directory under top (including top itself, but excluding
211# '.' and '..'), func(arg, dirname, filenames) is called, where
212# dirname is the name of the directory and filenames is the list
Guido van Rossum346f7af1997-12-05 19:04:51 +0000213# of files (and subdirectories etc.) in the directory.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000214# The func may modify the filenames list, to implement a filter,
Guido van Rossumc6360141990-10-13 19:23:40 +0000215# or to impose a different order of visiting.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000216
Guido van Rossumc6360141990-10-13 19:23:40 +0000217def walk(top, func, arg):
Tim Peterscf5e6a42001-10-10 04:16:20 +0000218 """Directory tree walk with callback function.
219
220 For each directory in the directory tree rooted at top (including top
221 itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
222 dirname is the name of the directory, and fnames a list of the names of
223 the files and subdirectories in dirname (excluding '.' and '..'). func
224 may modify the fnames list in-place (e.g. via del or slice assignment),
225 and walk will only recurse into the subdirectories whose names remain in
226 fnames; this can be used to implement a filter, or to impose a specific
227 order of visiting. No semantics are defined for, or required of, arg,
228 beyond that arg is always passed to func. It can be used, e.g., to pass
229 a filename pattern, or a mutable object designed to accumulate
230 statistics. Passing None for arg is common."""
Philip Jenveyd846f1d2009-05-08 02:28:39 +0000231 warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",
232 stacklevel=2)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000233 try:
234 names = os.listdir(top)
235 except os.error:
236 return
237 func(arg, top, names)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000238 for name in names:
Tim Peters2344fae2001-01-15 00:50:52 +0000239 name = join(top, name)
Guido van Rossuma490d582001-04-16 18:12:04 +0000240 try:
241 st = os.lstat(name)
242 except os.error:
243 continue
Neal Norwitzec7cf132002-06-06 18:16:14 +0000244 if stat.S_ISDIR(st.st_mode):
Tim Peters2344fae2001-01-15 00:50:52 +0000245 walk(name, func, arg)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000246
247
248# Expand paths beginning with '~' or '~user'.
249# '~' means $HOME; '~user' means that user's home directory.
250# If the path doesn't begin with '~', or if the user or $HOME is unknown,
251# the path is returned unchanged (leaving error reporting to whatever
252# function is called with the expanded path as argument).
253# See also module 'glob' for expansion of *, ? and [...] in pathnames.
254# (A function should also be defined to do full *sh-style environment
255# variable expansion.)
256
257def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000258 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000259 do nothing."""
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000260 if not path.startswith('~'):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000261 return path
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000262 i = path.find('/', 1)
263 if i < 0:
264 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000265 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000266 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000267 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000268 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000269 else:
270 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000271 else:
272 import pwd
273 try:
274 pwent = pwd.getpwnam(path[1:i])
275 except KeyError:
276 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000277 userhome = pwent.pw_dir
Jesus Ceaf2011e32012-05-10 05:01:11 +0200278 userhome = userhome.rstrip('/')
279 return (userhome + path[i:]) or '/'
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000280
281
282# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000283# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000284# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000285
286_varprog = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000287
288def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000289 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000290 are left unchanged."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000291 global _varprog
292 if '$' not in path:
293 return path
294 if not _varprog:
295 import re
296 _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
297 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000298 while True:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000299 m = _varprog.search(path, i)
300 if not m:
301 break
302 i, j = m.span(0)
303 name = m.group(1)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000304 if name.startswith('{') and name.endswith('}'):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000305 name = name[1:-1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000306 if name in os.environ:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000307 tail = path[j:]
308 path = path[:i] + os.environ[name]
309 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000310 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000311 else:
312 i = j
313 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000314
315
316# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
317# It should be understood that this may change the meaning of the path
318# if it contains symbolic links!
319
320def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000321 """Normalize path, eliminating double slashes, etc."""
Ezio Melottib5689de2010-01-12 03:32:05 +0000322 # Preserve unicode (if path is unicode)
Martin v. Löwised11a5d2012-05-20 10:42:17 +0200323 slash, dot = (u'/', u'.') if isinstance(path, _unicode) else ('/', '.')
Skip Montanaro018dfae2000-07-19 17:09:51 +0000324 if path == '':
Ezio Melottib5689de2010-01-12 03:32:05 +0000325 return dot
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000326 initial_slashes = path.startswith('/')
327 # POSIX allows one or two initial slashes, but treats three or more
328 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000329 if (initial_slashes and
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000330 path.startswith('//') and not path.startswith('///')):
331 initial_slashes = 2
Fred Drake22fb8392000-09-28 15:04:39 +0000332 comps = path.split('/')
Skip Montanaro018dfae2000-07-19 17:09:51 +0000333 new_comps = []
334 for comp in comps:
335 if comp in ('', '.'):
336 continue
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000337 if (comp != '..' or (not initial_slashes and not new_comps) or
Skip Montanaro018dfae2000-07-19 17:09:51 +0000338 (new_comps and new_comps[-1] == '..')):
339 new_comps.append(comp)
340 elif new_comps:
341 new_comps.pop()
342 comps = new_comps
Ezio Melottib5689de2010-01-12 03:32:05 +0000343 path = slash.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000344 if initial_slashes:
Ezio Melottib5689de2010-01-12 03:32:05 +0000345 path = slash*initial_slashes + path
346 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000347
348
Guido van Rossume294cf61999-01-29 18:05:18 +0000349def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000350 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000351 if not isabs(path):
Martin v. Löwised11a5d2012-05-20 10:42:17 +0200352 if isinstance(path, _unicode):
Ezio Melotti4cc80ca2010-02-20 08:09:39 +0000353 cwd = os.getcwdu()
354 else:
355 cwd = os.getcwd()
356 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000357 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000358
359
360# Return a canonical path (i.e. the absolute location of a file on the
361# filesystem).
362
363def realpath(filename):
364 """Return the canonical path of the specified filename, eliminating any
365symbolic links encountered in the path."""
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000366 if isabs(filename):
367 bits = ['/'] + filename.split('/')[1:]
368 else:
Georg Brandl268e61c2005-06-03 14:28:50 +0000369 bits = [''] + filename.split('/')
Tim Petersa45cacf2004-08-20 03:47:14 +0000370
Guido van Rossum83eeef42001-09-17 15:16:09 +0000371 for i in range(2, len(bits)+1):
372 component = join(*bits[0:i])
Brett Cannonf50299c2004-07-10 22:55:15 +0000373 # Resolve symbolic links.
Brett Cannondfa5d952004-07-11 19:16:21 +0000374 if islink(component):
Brett Cannonf50299c2004-07-10 22:55:15 +0000375 resolved = _resolve_link(component)
376 if resolved is None:
377 # Infinite loop -- return original component + rest of the path
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000378 return abspath(join(*([component] + bits[i:])))
Brett Cannonf50299c2004-07-10 22:55:15 +0000379 else:
380 newpath = join(*([resolved] + bits[i:]))
Tim Petersa45cacf2004-08-20 03:47:14 +0000381 return realpath(newpath)
Tim Petersb64bec32001-09-18 02:26:39 +0000382
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000383 return abspath(filename)
Tim Petersa45cacf2004-08-20 03:47:14 +0000384
Brett Cannonf50299c2004-07-10 22:55:15 +0000385
386def _resolve_link(path):
387 """Internal helper function. Takes a path and follows symlinks
Tim Peters182b5ac2004-07-18 06:16:08 +0000388 until we either arrive at something that isn't a symlink, or
Brett Cannonf50299c2004-07-10 22:55:15 +0000389 encounter a path we've seen before (meaning that there's a loop).
390 """
Benjamin Peterson1763f8a2009-01-27 03:07:53 +0000391 paths_seen = set()
Brett Cannonf50299c2004-07-10 22:55:15 +0000392 while islink(path):
Brett Cannondfa5d952004-07-11 19:16:21 +0000393 if path in paths_seen:
Brett Cannonf50299c2004-07-10 22:55:15 +0000394 # Already seen this path, so we must have a symlink loop
395 return None
Benjamin Peterson1763f8a2009-01-27 03:07:53 +0000396 paths_seen.add(path)
Brett Cannonf50299c2004-07-10 22:55:15 +0000397 # Resolve where the link points to
Brett Cannondfa5d952004-07-11 19:16:21 +0000398 resolved = os.readlink(path)
Andrew M. Kuchlingc75f1122004-08-02 14:54:16 +0000399 if not isabs(resolved):
Brett Cannonf50299c2004-07-10 22:55:15 +0000400 dir = dirname(path)
401 path = normpath(join(dir, resolved))
402 else:
403 path = normpath(resolved)
404 return path
405
Victor Stinner8fc843b2010-09-17 23:35:50 +0000406supports_unicode_filenames = (sys.platform == 'darwin')
Collin Winter6f187742007-03-16 22:16:08 +0000407
408def relpath(path, start=curdir):
409 """Return a relative version of a path"""
410
411 if not path:
412 raise ValueError("no path specified")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000413
Hirokazu Yamamoto50f7d7e2010-10-18 13:55:29 +0000414 start_list = [x for x in abspath(start).split(sep) if x]
415 path_list = [x for x in abspath(path).split(sep) if x]
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000416
Collin Winter6f187742007-03-16 22:16:08 +0000417 # Work out how much of the filepath is shared by start and path.
418 i = len(commonprefix([start_list, path_list]))
419
420 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Georg Brandl183a0842008-01-06 14:27:15 +0000421 if not rel_list:
422 return curdir
Collin Winter6f187742007-03-16 22:16:08 +0000423 return join(*rel_list)