blob: b29eedc38b56723e3c84358326eaf4b84fef0f07 [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
Guido van Rossumc6360141990-10-13 19:23:40 +000015
Skip Montanaroc62c81e2001-02-12 02:00:42 +000016__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
17 "basename","dirname","commonprefix","getsize","getmtime",
Martin v. Löwis96a60e42002-12-31 13:11:54 +000018 "getatime","getctime","islink","exists","isdir","isfile","ismount",
Skip Montanaroc62c81e2001-02-12 02:00:42 +000019 "walk","expanduser","expandvars","normpath","abspath",
Neal Norwitz61cdac62003-01-03 18:01:57 +000020 "samefile","sameopenfile","samestat",
Skip Montanaro117910d2003-02-14 19:35:31 +000021 "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000022 "devnull","realpath","supports_unicode_filenames"]
Guido van Rossumc6360141990-10-13 19:23:40 +000023
Skip Montanaro117910d2003-02-14 19:35:31 +000024# strings representing various path-related bits and pieces
25curdir = '.'
26pardir = '..'
27extsep = '.'
28sep = '/'
29pathsep = ':'
30defpath = ':/bin:/usr/bin'
31altsep = None
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000032devnull = '/dev/null'
Skip Montanaro117910d2003-02-14 19:35:31 +000033
Guido van Rossum7ac48781992-01-14 18:29:32 +000034# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
35# On MS-DOS this may also turn slashes into backslashes; however, other
36# normalizations (such as optimizing '../' away) are not allowed
37# (another function should be defined to do that).
38
39def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000040 """Normalize case of pathname. Has no effect under Posix"""
41 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000042
43
Jeremy Hyltona05e2932000-06-28 14:48:01 +000044# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000045# Trivial in Posix, harder on the Mac or MS-DOS.
46
47def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000048 """Test whether a path is absolute"""
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000049 return s.startswith('/')
Guido van Rossum7ac48781992-01-14 18:29:32 +000050
51
Barry Warsaw384d2491997-02-18 21:53:25 +000052# Join pathnames.
53# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000054# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000055
Barry Warsaw384d2491997-02-18 21:53:25 +000056def join(a, *p):
Guido van Rossum346f7af1997-12-05 19:04:51 +000057 """Join two or more pathname components, inserting '/' as needed"""
58 path = a
59 for b in p:
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000060 if b.startswith('/'):
Guido van Rossum346f7af1997-12-05 19:04:51 +000061 path = b
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000062 elif path == '' or path.endswith('/'):
63 path += b
Guido van Rossum346f7af1997-12-05 19:04:51 +000064 else:
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000065 path += '/' + b
Guido van Rossum346f7af1997-12-05 19:04:51 +000066 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000067
68
Guido van Rossum26847381992-03-31 18:54:35 +000069# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000070# rest). If the path ends in '/', tail will be empty. If there is no
71# '/' in the path, head will be empty.
72# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000073
Guido van Rossumc6360141990-10-13 19:23:40 +000074def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +000075 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +000076 everything after the final slash. Either part may be empty."""
Fred Drake22fb8392000-09-28 15:04:39 +000077 i = p.rfind('/') + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +000078 head, tail = p[:i], p[i:]
Fred Drake8152d322000-12-12 23:20:45 +000079 if head and head != '/'*len(head):
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000080 head = head.rstrip('/')
Guido van Rossum346f7af1997-12-05 19:04:51 +000081 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +000082
83
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000084# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +000085# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000086# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +000087# It is always true that root + ext == p.
88
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000089def splitext(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +000090 """Split the extension from a pathname. Extension is everything from the
Fred Drakec0ab93e2000-09-28 16:22:52 +000091 last dot to the end. Returns "(root, ext)", either part may be empty."""
Martin v. Löwisde333792002-12-12 20:30:20 +000092 i = p.rfind('.')
93 if i<=p.rfind('/'):
94 return p, ''
95 else:
96 return p[:i], p[i:]
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000097
98
Guido van Rossum221df241995-08-07 20:17:55 +000099# Split a pathname into a drive specification and the rest of the
100# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
101
102def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000103 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000104 empty."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000105 return '', p
Guido van Rossum221df241995-08-07 20:17:55 +0000106
107
Guido van Rossumc6360141990-10-13 19:23:40 +0000108# Return the tail (basename) part of a path.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000109
Guido van Rossumc6360141990-10-13 19:23:40 +0000110def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000111 """Returns the final component of a pathname"""
112 return split(p)[1]
Guido van Rossumc6360141990-10-13 19:23:40 +0000113
114
Guido van Rossumc629d341992-11-05 10:43:02 +0000115# Return the head (dirname) part of a path.
116
117def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000118 """Returns the directory component of a pathname"""
119 return split(p)[0]
Guido van Rossumc629d341992-11-05 10:43:02 +0000120
121
Guido van Rossumc6360141990-10-13 19:23:40 +0000122# Return the longest prefix of all list elements.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000123
Guido van Rossumc6360141990-10-13 19:23:40 +0000124def commonprefix(m):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000125 "Given a list of pathnames, returns the longest common leading component"
126 if not m: return ''
Raymond Hettinger74bb7f02003-12-31 22:44:29 +0000127 s1 = min(m)
128 s2 = max(m)
129 n = min(len(s1), len(s2))
130 for i in xrange(n):
131 if s1[i] != s2[i]:
132 return s1[:i]
133 return s1[:n]
Guido van Rossumc6360141990-10-13 19:23:40 +0000134
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000135# Get size, mtime, atime of files.
136
137def getsize(filename):
138 """Return the size of a file, reported by os.stat()."""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000139 return os.stat(filename).st_size
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000140
141def getmtime(filename):
142 """Return the last modification time of a file, reported by os.stat()."""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000143 return os.stat(filename).st_mtime
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000144
145def getatime(filename):
146 """Return the last access time of a file, reported by os.stat()."""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000147 return os.stat(filename).st_atime
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000148
Martin v. Löwis96a60e42002-12-31 13:11:54 +0000149def getctime(filename):
Fred Drake1cd6e4d2004-05-12 03:51:40 +0000150 """Return the metadata change time of a file, reported by os.stat()."""
Martin v. Löwis96a60e42002-12-31 13:11:54 +0000151 return os.stat(filename).st_ctime
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000152
Guido van Rossum7ac48781992-01-14 18:29:32 +0000153# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000154# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000155
156def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000157 """Test whether a path is a symbolic link"""
158 try:
159 st = os.lstat(path)
160 except (os.error, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000161 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000162 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000163
164
165# Does a path exist?
166# This is false for dangling symbolic links.
167
Guido van Rossumc6360141990-10-13 19:23:40 +0000168def exists(path):
Tim Petersbc0e9102002-04-04 22:55:58 +0000169 """Test whether a path exists. Returns False for broken symbolic links"""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000170 try:
171 st = os.stat(path)
172 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000173 return False
174 return True
Guido van Rossumc6360141990-10-13 19:23:40 +0000175
176
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000177# Being true for dangling symbolic links is also useful.
178
179def lexists(path):
180 """Test whether a path exists. Returns True for broken symbolic links"""
181 try:
182 st = os.lstat(path)
183 except os.error:
184 return False
185 return True
186
187
Guido van Rossumd3876d31996-07-23 03:47:28 +0000188# Is a path a directory?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000189# This follows symbolic links, so both islink() and isdir() can be true
190# for the same path.
191
Guido van Rossumc6360141990-10-13 19:23:40 +0000192def isdir(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000193 """Test whether a path is a directory"""
194 try:
195 st = os.stat(path)
196 except os.error:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000197 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000198 return stat.S_ISDIR(st.st_mode)
Guido van Rossumc6360141990-10-13 19:23:40 +0000199
200
Guido van Rossum26847381992-03-31 18:54:35 +0000201# Is a path a regular file?
Guido van Rossumb6775db1994-08-01 11:34:53 +0000202# This follows symbolic links, so both islink() and isfile() can be true
Guido van Rossum7ac48781992-01-14 18:29:32 +0000203# for the same path.
204
205def isfile(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000206 """Test whether a path is a regular file"""
207 try:
208 st = os.stat(path)
209 except os.error:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000210 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000211 return stat.S_ISREG(st.st_mode)
Guido van Rossumc6360141990-10-13 19:23:40 +0000212
213
Guido van Rossumd3778f91991-11-12 15:37:40 +0000214# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000215
Guido van Rossumd3778f91991-11-12 15:37:40 +0000216def samefile(f1, f2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000217 """Test whether two pathnames reference the same actual file"""
218 s1 = os.stat(f1)
219 s2 = os.stat(f2)
220 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000221
222
223# Are two open files really referencing the same file?
224# (Not necessarily the same file descriptor!)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000225
Guido van Rossumd3778f91991-11-12 15:37:40 +0000226def sameopenfile(fp1, fp2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000227 """Test whether two open file objects reference the same file"""
228 s1 = os.fstat(fp1)
229 s2 = os.fstat(fp2)
230 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000231
232
233# Are two stat buffers (obtained from stat, fstat or lstat)
234# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000235
Guido van Rossumd3778f91991-11-12 15:37:40 +0000236def samestat(s1, s2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000237 """Test whether two stat buffers reference the same file"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000238 return s1.st_ino == s2.st_ino and \
239 s1.st_dev == s2.st_dev
Guido van Rossumc6360141990-10-13 19:23:40 +0000240
241
242# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000243# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000244
Guido van Rossumc6360141990-10-13 19:23:40 +0000245def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000246 """Test whether a path is a mount point"""
247 try:
248 s1 = os.stat(path)
249 s2 = os.stat(join(path, '..'))
250 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000251 return False # It doesn't exist -- so not a mount point :-)
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000252 dev1 = s1.st_dev
253 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000254 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000255 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000256 ino1 = s1.st_ino
257 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000258 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000259 return True # path/.. is the same i-node as path
260 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000261
262
263# Directory tree walk.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000264# For each directory under top (including top itself, but excluding
265# '.' and '..'), func(arg, dirname, filenames) is called, where
266# dirname is the name of the directory and filenames is the list
Guido van Rossum346f7af1997-12-05 19:04:51 +0000267# of files (and subdirectories etc.) in the directory.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000268# The func may modify the filenames list, to implement a filter,
Guido van Rossumc6360141990-10-13 19:23:40 +0000269# or to impose a different order of visiting.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000270
Guido van Rossumc6360141990-10-13 19:23:40 +0000271def walk(top, func, arg):
Tim Peterscf5e6a42001-10-10 04:16:20 +0000272 """Directory tree walk with callback function.
273
274 For each directory in the directory tree rooted at top (including top
275 itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
276 dirname is the name of the directory, and fnames a list of the names of
277 the files and subdirectories in dirname (excluding '.' and '..'). func
278 may modify the fnames list in-place (e.g. via del or slice assignment),
279 and walk will only recurse into the subdirectories whose names remain in
280 fnames; this can be used to implement a filter, or to impose a specific
281 order of visiting. No semantics are defined for, or required of, arg,
282 beyond that arg is always passed to func. It can be used, e.g., to pass
283 a filename pattern, or a mutable object designed to accumulate
284 statistics. Passing None for arg is common."""
285
Guido van Rossum346f7af1997-12-05 19:04:51 +0000286 try:
287 names = os.listdir(top)
288 except os.error:
289 return
290 func(arg, top, names)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000291 for name in names:
Tim Peters2344fae2001-01-15 00:50:52 +0000292 name = join(top, name)
Guido van Rossuma490d582001-04-16 18:12:04 +0000293 try:
294 st = os.lstat(name)
295 except os.error:
296 continue
Neal Norwitzec7cf132002-06-06 18:16:14 +0000297 if stat.S_ISDIR(st.st_mode):
Tim Peters2344fae2001-01-15 00:50:52 +0000298 walk(name, func, arg)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000299
300
301# Expand paths beginning with '~' or '~user'.
302# '~' means $HOME; '~user' means that user's home directory.
303# If the path doesn't begin with '~', or if the user or $HOME is unknown,
304# the path is returned unchanged (leaving error reporting to whatever
305# function is called with the expanded path as argument).
306# See also module 'glob' for expansion of *, ? and [...] in pathnames.
307# (A function should also be defined to do full *sh-style environment
308# variable expansion.)
309
310def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000311 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000312 do nothing."""
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000313 if not path.startswith('~'):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000314 return path
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000315 i = path.find('/', 1)
316 if i < 0:
317 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000318 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000319 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000320 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000321 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000322 else:
323 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000324 else:
325 import pwd
326 try:
327 pwent = pwd.getpwnam(path[1:i])
328 except KeyError:
329 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000330 userhome = pwent.pw_dir
331 if userhome.endswith('/'):
332 i += 1
Guido van Rossum346f7af1997-12-05 19:04:51 +0000333 return userhome + path[i:]
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000334
335
336# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000337# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000338# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000339
340_varprog = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000341
342def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000343 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000344 are left unchanged."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000345 global _varprog
346 if '$' not in path:
347 return path
348 if not _varprog:
349 import re
350 _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
351 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000352 while True:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000353 m = _varprog.search(path, i)
354 if not m:
355 break
356 i, j = m.span(0)
357 name = m.group(1)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000358 if name.startswith('{') and name.endswith('}'):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000359 name = name[1:-1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000360 if name in os.environ:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000361 tail = path[j:]
362 path = path[:i] + os.environ[name]
363 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000364 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000365 else:
366 i = j
367 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000368
369
370# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
371# It should be understood that this may change the meaning of the path
372# if it contains symbolic links!
373
374def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000375 """Normalize path, eliminating double slashes, etc."""
Skip Montanaro018dfae2000-07-19 17:09:51 +0000376 if path == '':
377 return '.'
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000378 initial_slashes = path.startswith('/')
379 # POSIX allows one or two initial slashes, but treats three or more
380 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000381 if (initial_slashes and
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000382 path.startswith('//') and not path.startswith('///')):
383 initial_slashes = 2
Fred Drake22fb8392000-09-28 15:04:39 +0000384 comps = path.split('/')
Skip Montanaro018dfae2000-07-19 17:09:51 +0000385 new_comps = []
386 for comp in comps:
387 if comp in ('', '.'):
388 continue
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000389 if (comp != '..' or (not initial_slashes and not new_comps) or
Skip Montanaro018dfae2000-07-19 17:09:51 +0000390 (new_comps and new_comps[-1] == '..')):
391 new_comps.append(comp)
392 elif new_comps:
393 new_comps.pop()
394 comps = new_comps
Fred Drake22fb8392000-09-28 15:04:39 +0000395 path = '/'.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000396 if initial_slashes:
397 path = '/'*initial_slashes + path
Skip Montanaro018dfae2000-07-19 17:09:51 +0000398 return path or '.'
Guido van Rossume294cf61999-01-29 18:05:18 +0000399
400
Guido van Rossume294cf61999-01-29 18:05:18 +0000401def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000402 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000403 if not isabs(path):
404 path = join(os.getcwd(), path)
405 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000406
407
408# Return a canonical path (i.e. the absolute location of a file on the
409# filesystem).
410
411def realpath(filename):
412 """Return the canonical path of the specified filename, eliminating any
413symbolic links encountered in the path."""
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000414 if isabs(filename):
415 bits = ['/'] + filename.split('/')[1:]
416 else:
417 bits = filename.split('/')
Tim Petersa45cacf2004-08-20 03:47:14 +0000418
Guido van Rossum83eeef42001-09-17 15:16:09 +0000419 for i in range(2, len(bits)+1):
420 component = join(*bits[0:i])
Brett Cannonf50299c2004-07-10 22:55:15 +0000421 # Resolve symbolic links.
Brett Cannondfa5d952004-07-11 19:16:21 +0000422 if islink(component):
Brett Cannonf50299c2004-07-10 22:55:15 +0000423 resolved = _resolve_link(component)
424 if resolved is None:
425 # Infinite loop -- return original component + rest of the path
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000426 return abspath(join(*([component] + bits[i:])))
Brett Cannonf50299c2004-07-10 22:55:15 +0000427 else:
428 newpath = join(*([resolved] + bits[i:]))
Tim Petersa45cacf2004-08-20 03:47:14 +0000429 return realpath(newpath)
Tim Petersb64bec32001-09-18 02:26:39 +0000430
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000431 return abspath(filename)
Tim Petersa45cacf2004-08-20 03:47:14 +0000432
Brett Cannonf50299c2004-07-10 22:55:15 +0000433
434def _resolve_link(path):
435 """Internal helper function. Takes a path and follows symlinks
Tim Peters182b5ac2004-07-18 06:16:08 +0000436 until we either arrive at something that isn't a symlink, or
Brett Cannonf50299c2004-07-10 22:55:15 +0000437 encounter a path we've seen before (meaning that there's a loop).
438 """
439 paths_seen = []
440 while islink(path):
Brett Cannondfa5d952004-07-11 19:16:21 +0000441 if path in paths_seen:
Brett Cannonf50299c2004-07-10 22:55:15 +0000442 # Already seen this path, so we must have a symlink loop
443 return None
Brett Cannondfa5d952004-07-11 19:16:21 +0000444 paths_seen.append(path)
Brett Cannonf50299c2004-07-10 22:55:15 +0000445 # Resolve where the link points to
Brett Cannondfa5d952004-07-11 19:16:21 +0000446 resolved = os.readlink(path)
Andrew M. Kuchlingc75f1122004-08-02 14:54:16 +0000447 if not isabs(resolved):
Brett Cannonf50299c2004-07-10 22:55:15 +0000448 dir = dirname(path)
449 path = normpath(join(dir, resolved))
450 else:
451 path = normpath(resolved)
452 return path
453
Just van Rossum2d4e9882003-07-17 15:11:49 +0000454supports_unicode_filenames = False