blob: b1e1a9255e6c98f324a1ee473c12dcdf83f7874d [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 Rossumf0af3e32008-10-02 18:55:37 +000014import sys
Guido van Rossum40d93041990-10-21 16:17:34 +000015import stat
Guido van Rossumd8faa362007-04-27 19:54:29 +000016import genericpath
Thomas Wouters89f507f2006-12-13 04:49:30 +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",
Benjamin Petersond71ca412008-05-08 23:44:58 +000022 "ismount", "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",
Guido van Rossumd8faa362007-04-27 19:54:29 +000025 "devnull","realpath","supports_unicode_filenames","relpath"]
Guido van Rossumc6360141990-10-13 19:23:40 +000026
Guido van Rossumf0af3e32008-10-02 18:55:37 +000027# Strings representing various path-related bits and pieces.
28# These are primarily for export; internally, they are hardcoded.
Skip Montanaro117910d2003-02-14 19:35:31 +000029curdir = '.'
30pardir = '..'
31extsep = '.'
32sep = '/'
33pathsep = ':'
34defpath = ':/bin:/usr/bin'
35altsep = None
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000036devnull = '/dev/null'
Skip Montanaro117910d2003-02-14 19:35:31 +000037
Guido van Rossumf0af3e32008-10-02 18:55:37 +000038def _get_sep(path):
39 if isinstance(path, bytes):
40 return b'/'
41 else:
42 return '/'
43
Guido van Rossum7ac48781992-01-14 18:29:32 +000044# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
45# On MS-DOS this may also turn slashes into backslashes; however, other
46# normalizations (such as optimizing '../' away) are not allowed
47# (another function should be defined to do that).
48
49def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000050 """Normalize case of pathname. Has no effect under Posix"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000051 # TODO: on Mac OS X, this should really return s.lower().
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +000052 if not isinstance(s, (bytes, str)):
53 raise TypeError("normcase() argument must be str or bytes, "
54 "not '{}'".format(s.__class__.__name__))
Guido van Rossum346f7af1997-12-05 19:04:51 +000055 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000056
57
Jeremy Hyltona05e2932000-06-28 14:48:01 +000058# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000059# Trivial in Posix, harder on the Mac or MS-DOS.
60
61def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000062 """Test whether a path is absolute"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000063 sep = _get_sep(s)
64 return s.startswith(sep)
Guido van Rossum7ac48781992-01-14 18:29:32 +000065
66
Barry Warsaw384d2491997-02-18 21:53:25 +000067# Join pathnames.
68# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000069# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000070
Barry Warsaw384d2491997-02-18 21:53:25 +000071def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +000072 """Join two or more pathname components, inserting '/' as needed.
73 If any component is an absolute path, all previous path components
R David Murraye3de1752012-07-21 14:33:56 -040074 will be discarded. An empty last part will result in a path that
75 ends with a separator."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000076 sep = _get_sep(a)
Guido van Rossum346f7af1997-12-05 19:04:51 +000077 path = a
Hynek Schlawack47749462012-07-15 16:21:30 +020078 try:
79 for b in p:
80 if b.startswith(sep):
81 path = b
82 elif not path or path.endswith(sep):
83 path += b
84 else:
85 path += sep + b
86 except TypeError:
Hynek Schlawackc5a45662012-07-17 13:05:43 +020087 valid_types = all(isinstance(s, (str, bytes, bytearray))
88 for s in (a, ) + p)
89 if valid_types:
90 # Must have a mixture of text and binary data
Hynek Schlawack9ac4d882012-07-15 16:46:23 +020091 raise TypeError("Can't mix strings and bytes in path "
92 "components.") from None
Hynek Schlawackc5a45662012-07-17 13:05:43 +020093 raise
Guido van Rossum346f7af1997-12-05 19:04:51 +000094 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000095
96
Guido van Rossum26847381992-03-31 18:54:35 +000097# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000098# rest). If the path ends in '/', tail will be empty. If there is no
99# '/' in the path, head will be empty.
100# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000101
Guido van Rossumc6360141990-10-13 19:23:40 +0000102def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000103 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +0000104 everything after the final slash. Either part may be empty."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000105 sep = _get_sep(p)
106 i = p.rfind(sep) + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +0000107 head, tail = p[:i], p[i:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000108 if head and head != sep*len(head):
109 head = head.rstrip(sep)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000110 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +0000111
112
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000113# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +0000114# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000115# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000116# It is always true that root + ext == p.
117
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000118def splitext(p):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000119 if isinstance(p, bytes):
120 sep = b'/'
121 extsep = b'.'
122 else:
123 sep = '/'
124 extsep = '.'
125 return genericpath._splitext(p, sep, None, extsep)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000127
Guido van Rossum221df241995-08-07 20:17:55 +0000128# Split a pathname into a drive specification and the rest of the
129# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
130
131def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000132 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000133 empty."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000134 return p[:0], p
Guido van Rossum221df241995-08-07 20:17:55 +0000135
136
Thomas Wouters89f507f2006-12-13 04:49:30 +0000137# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000138
Guido van Rossumc6360141990-10-13 19:23:40 +0000139def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000140 """Returns the final component of a pathname"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000141 sep = _get_sep(p)
142 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000143 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000144
145
Thomas Wouters89f507f2006-12-13 04:49:30 +0000146# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000147
148def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000149 """Returns the directory component of a pathname"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000150 sep = _get_sep(p)
151 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000152 head = p[:i]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000153 if head and head != sep*len(head):
154 head = head.rstrip(sep)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000155 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000156
157
Guido van Rossum7ac48781992-01-14 18:29:32 +0000158# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000159# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000160
161def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000162 """Test whether a path is a symbolic link"""
163 try:
164 st = os.lstat(path)
165 except (os.error, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000166 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000167 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000168
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000169# Being true for dangling symbolic links is also useful.
170
171def lexists(path):
172 """Test whether a path exists. Returns True for broken symbolic links"""
173 try:
Georg Brandl89fad142010-03-14 10:23:39 +0000174 os.lstat(path)
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000175 except os.error:
176 return False
177 return True
178
179
Guido van Rossumd3778f91991-11-12 15:37:40 +0000180# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000181
Guido van Rossumd3778f91991-11-12 15:37:40 +0000182def samefile(f1, f2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000183 """Test whether two pathnames reference the same actual file"""
184 s1 = os.stat(f1)
185 s2 = os.stat(f2)
186 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000187
188
189# Are two open files really referencing the same file?
190# (Not necessarily the same file descriptor!)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000191
Guido van Rossumd3778f91991-11-12 15:37:40 +0000192def sameopenfile(fp1, fp2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000193 """Test whether two open file objects reference the same file"""
194 s1 = os.fstat(fp1)
195 s2 = os.fstat(fp2)
196 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000197
198
199# Are two stat buffers (obtained from stat, fstat or lstat)
200# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000201
Guido van Rossumd3778f91991-11-12 15:37:40 +0000202def samestat(s1, s2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000203 """Test whether two stat buffers reference the same file"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000204 return s1.st_ino == s2.st_ino and \
205 s1.st_dev == s2.st_dev
Guido van Rossumc6360141990-10-13 19:23:40 +0000206
207
208# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000209# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000210
Guido van Rossumc6360141990-10-13 19:23:40 +0000211def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000212 """Test whether a path is a mount point"""
Georg Brandle6c59502010-08-01 15:30:56 +0000213 if islink(path):
214 # A symlink can never be a mount point
215 return False
Guido van Rossum346f7af1997-12-05 19:04:51 +0000216 try:
Christian Heimesfaf2f632008-01-06 16:59:19 +0000217 s1 = os.lstat(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000218 if isinstance(path, bytes):
219 parent = join(path, b'..')
220 else:
221 parent = join(path, '..')
222 s2 = os.lstat(parent)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000223 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000224 return False # It doesn't exist -- so not a mount point :-)
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000225 dev1 = s1.st_dev
226 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000227 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000228 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000229 ino1 = s1.st_ino
230 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000231 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000232 return True # path/.. is the same i-node as path
233 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000234
235
Guido van Rossum7ac48781992-01-14 18:29:32 +0000236# Expand paths beginning with '~' or '~user'.
237# '~' means $HOME; '~user' means that user's home directory.
238# If the path doesn't begin with '~', or if the user or $HOME is unknown,
239# the path is returned unchanged (leaving error reporting to whatever
240# function is called with the expanded path as argument).
241# See also module 'glob' for expansion of *, ? and [...] in pathnames.
242# (A function should also be defined to do full *sh-style environment
243# variable expansion.)
244
245def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000246 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000247 do nothing."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000248 if isinstance(path, bytes):
249 tilde = b'~'
250 else:
251 tilde = '~'
252 if not path.startswith(tilde):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000253 return path
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000254 sep = _get_sep(path)
255 i = path.find(sep, 1)
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000256 if i < 0:
257 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000258 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000259 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000260 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000261 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000262 else:
263 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000264 else:
265 import pwd
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000266 name = path[1:i]
267 if isinstance(name, bytes):
268 name = str(name, 'ASCII')
Guido van Rossum346f7af1997-12-05 19:04:51 +0000269 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000270 pwent = pwd.getpwnam(name)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000271 except KeyError:
272 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000273 userhome = pwent.pw_dir
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000274 if isinstance(path, bytes):
Victor Stinner16004ac2010-09-29 16:59:18 +0000275 userhome = os.fsencode(userhome)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000276 root = b'/'
277 else:
278 root = '/'
Jesus Cea7f0d8882012-05-10 05:10:50 +0200279 userhome = userhome.rstrip(root)
280 return (userhome + path[i:]) or root
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000281
282
283# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000285# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000286
287_varprog = None
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000288_varprogb = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000289
290def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000291 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000292 are left unchanged."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000293 global _varprog, _varprogb
294 if isinstance(path, bytes):
295 if b'$' not in path:
296 return path
297 if not _varprogb:
298 import re
299 _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII)
300 search = _varprogb.search
301 start = b'{'
302 end = b'}'
303 else:
304 if '$' not in path:
305 return path
306 if not _varprog:
307 import re
308 _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
309 search = _varprog.search
310 start = '{'
311 end = '}'
Guido van Rossum346f7af1997-12-05 19:04:51 +0000312 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000313 while True:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000314 m = search(path, i)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000315 if not m:
316 break
317 i, j = m.span(0)
318 name = m.group(1)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000319 if name.startswith(start) and name.endswith(end):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000320 name = name[1:-1]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000321 if isinstance(name, bytes):
322 name = str(name, 'ASCII')
Raymond Hettinger54f02222002-06-01 14:18:47 +0000323 if name in os.environ:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000324 tail = path[j:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000325 value = os.environ[name]
326 if isinstance(path, bytes):
327 value = value.encode('ASCII')
328 path = path[:i] + value
Guido van Rossum346f7af1997-12-05 19:04:51 +0000329 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000330 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000331 else:
332 i = j
333 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000334
335
336# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
337# It should be understood that this may change the meaning of the path
338# if it contains symbolic links!
339
340def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000341 """Normalize path, eliminating double slashes, etc."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000342 if isinstance(path, bytes):
343 sep = b'/'
344 empty = b''
345 dot = b'.'
346 dotdot = b'..'
347 else:
348 sep = '/'
349 empty = ''
350 dot = '.'
351 dotdot = '..'
352 if path == empty:
353 return dot
354 initial_slashes = path.startswith(sep)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000355 # POSIX allows one or two initial slashes, but treats three or more
356 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000357 if (initial_slashes and
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000358 path.startswith(sep*2) and not path.startswith(sep*3)):
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000359 initial_slashes = 2
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000360 comps = path.split(sep)
Skip Montanaro018dfae2000-07-19 17:09:51 +0000361 new_comps = []
362 for comp in comps:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000363 if comp in (empty, dot):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000364 continue
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000365 if (comp != dotdot or (not initial_slashes and not new_comps) or
366 (new_comps and new_comps[-1] == dotdot)):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000367 new_comps.append(comp)
368 elif new_comps:
369 new_comps.pop()
370 comps = new_comps
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000371 path = sep.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000372 if initial_slashes:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000373 path = sep*initial_slashes + path
374 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000375
376
Guido van Rossume294cf61999-01-29 18:05:18 +0000377def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000378 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000379 if not isabs(path):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000380 if isinstance(path, bytes):
381 cwd = os.getcwdb()
382 else:
383 cwd = os.getcwd()
384 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000385 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000386
387
388# Return a canonical path (i.e. the absolute location of a file on the
389# filesystem).
390
391def realpath(filename):
392 """Return the canonical path of the specified filename, eliminating any
393symbolic links encountered in the path."""
Serhiy Storchakadf326912013-02-10 12:22:07 +0200394 path, ok = _joinrealpath(filename[:0], filename, {})
395 return abspath(path)
396
397# Join two paths, normalizing ang eliminating any symbolic links
398# encountered in the second path.
399def _joinrealpath(path, rest, seen):
400 if isinstance(path, bytes):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000401 sep = b'/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200402 curdir = b'.'
403 pardir = b'..'
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000404 else:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000405 sep = '/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200406 curdir = '.'
407 pardir = '..'
Tim Petersa45cacf2004-08-20 03:47:14 +0000408
Serhiy Storchakadf326912013-02-10 12:22:07 +0200409 if isabs(rest):
410 rest = rest[1:]
411 path = sep
412
413 while rest:
414 name, _, rest = rest.partition(sep)
415 if not name or name == curdir:
416 # current dir
417 continue
418 if name == pardir:
419 # parent dir
420 if path:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200421 path, name = split(path)
422 if name == pardir:
423 path = join(path, pardir, pardir)
Brett Cannonf50299c2004-07-10 22:55:15 +0000424 else:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200425 path = pardir
Serhiy Storchakadf326912013-02-10 12:22:07 +0200426 continue
427 newpath = join(path, name)
428 if not islink(newpath):
429 path = newpath
430 continue
431 # Resolve the symbolic link
432 if newpath in seen:
433 # Already seen this path
434 path = seen[newpath]
435 if path is not None:
436 # use cached value
437 continue
438 # The symlink is not resolved, so we must have a symlink loop.
439 # Return already resolved part + rest of the path unchanged.
440 return join(newpath, rest), False
441 seen[newpath] = None # not resolved symlink
442 path, ok = _joinrealpath(path, os.readlink(newpath), seen)
443 if not ok:
444 return join(path, rest), False
445 seen[newpath] = path # resolved symlink
Tim Petersb64bec32001-09-18 02:26:39 +0000446
Serhiy Storchakadf326912013-02-10 12:22:07 +0200447 return path, True
Tim Petersa45cacf2004-08-20 03:47:14 +0000448
Brett Cannonf50299c2004-07-10 22:55:15 +0000449
Victor Stinnere797c162010-09-17 23:34:26 +0000450supports_unicode_filenames = (sys.platform == 'darwin')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000452def relpath(path, start=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000453 """Return a relative version of a path"""
454
455 if not path:
456 raise ValueError("no path specified")
457
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000458 if isinstance(path, bytes):
459 curdir = b'.'
460 sep = b'/'
461 pardir = b'..'
462 else:
463 curdir = '.'
464 sep = '/'
465 pardir = '..'
466
467 if start is None:
468 start = curdir
469
Hirokazu Yamamotob08820a2010-10-18 12:13:18 +0000470 start_list = [x for x in abspath(start).split(sep) if x]
471 path_list = [x for x in abspath(path).split(sep) if x]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472
473 # Work out how much of the filepath is shared by start and path.
474 i = len(commonprefix([start_list, path_list]))
475
476 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Christian Heimesfaf2f632008-01-06 16:59:19 +0000477 if not rel_list:
478 return curdir
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479 return join(*rel_list)