blob: 014dfe2798390f5e1058e3d561906c38a3c88863 [file] [log] [blame]
Guido van Rossumd3876d31996-07-23 03:47:28 +00001# Module 'posixpath' -- common operations on Posix pathnames.
2# Some of this can actually be useful on non-Posix systems too, e.g.
3# for manipulation of the pathname component of URLs.
4# The "os.path" name is an alias for this module on Posix systems;
5# on other systems (e.g. Mac, Windows), os.path provides the same
6# operations in a manner specific to that platform, and is an alias
7# to another module (e.g. macpath, ntpath).
Guido van Rossumc6360141990-10-13 19:23:40 +00008
Guido van Rossumd3876d31996-07-23 03:47:28 +00009import os
Guido van Rossum40d93041990-10-21 16:17:34 +000010import stat
Guido van Rossumc6360141990-10-13 19:23:40 +000011
12
Guido van Rossum7ac48781992-01-14 18:29:32 +000013# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
14# On MS-DOS this may also turn slashes into backslashes; however, other
15# normalizations (such as optimizing '../' away) are not allowed
16# (another function should be defined to do that).
17
18def normcase(s):
19 return s
20
21
22# Return wheter a path is absolute.
23# Trivial in Posix, harder on the Mac or MS-DOS.
24
25def isabs(s):
26 return s[:1] == '/'
27
28
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000029# Join two pathnames.
Guido van Rossum7ac48781992-01-14 18:29:32 +000030# Ignore the first part if the second part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000031# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000032
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000033def join(a, b):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000034 if b[:1] == '/': return b
35 if a == '' or a[-1:] == '/': return a + b
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000036 # Note: join('x', '') returns 'x/'; is this what we want?
Guido van Rossumc6360141990-10-13 19:23:40 +000037 return a + '/' + b
38
39
Guido van Rossum26847381992-03-31 18:54:35 +000040# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000041# rest). If the path ends in '/', tail will be empty. If there is no
42# '/' in the path, head will be empty.
43# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000044
Guido van Rossumc6360141990-10-13 19:23:40 +000045def split(p):
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000046 import string
47 i = string.rfind(p, '/') + 1
48 head, tail = p[:i], p[i:]
49 if head and head <> '/'*len(head):
Guido van Rossum26847381992-03-31 18:54:35 +000050 while head[-1] == '/':
51 head = head[:-1]
Guido van Rossumc6360141990-10-13 19:23:40 +000052 return head, tail
53
54
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000055# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +000056# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000057# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +000058# It is always true that root + ext == p.
59
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000060def splitext(p):
61 root, ext = '', ''
62 for c in p:
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000063 if c == '/':
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000064 root, ext = root + ext + c, ''
Sjoerd Mullender43598601994-12-14 15:29:17 +000065 elif c == '.':
66 if ext:
67 root, ext = root + ext, c
68 else:
69 ext = c
70 elif ext:
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000071 ext = ext + c
72 else:
73 root = root + c
74 return root, ext
75
76
Guido van Rossum221df241995-08-07 20:17:55 +000077# Split a pathname into a drive specification and the rest of the
78# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
79
80def splitdrive(p):
81 return '', p
82
83
Guido van Rossumc6360141990-10-13 19:23:40 +000084# Return the tail (basename) part of a path.
Guido van Rossum7ac48781992-01-14 18:29:32 +000085
Guido van Rossumc6360141990-10-13 19:23:40 +000086def basename(p):
87 return split(p)[1]
88
89
Guido van Rossumc629d341992-11-05 10:43:02 +000090# Return the head (dirname) part of a path.
91
92def dirname(p):
93 return split(p)[0]
94
95
Guido van Rossumc6360141990-10-13 19:23:40 +000096# Return the longest prefix of all list elements.
Guido van Rossum7ac48781992-01-14 18:29:32 +000097
Guido van Rossumc6360141990-10-13 19:23:40 +000098def commonprefix(m):
99 if not m: return ''
100 prefix = m[0]
101 for item in m:
102 for i in range(len(prefix)):
103 if prefix[:i+1] <> item[:i+1]:
104 prefix = prefix[:i]
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000105 if i == 0: return ''
Guido van Rossumc6360141990-10-13 19:23:40 +0000106 break
107 return prefix
108
109
Guido van Rossum7ac48781992-01-14 18:29:32 +0000110# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000111# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000112
113def islink(path):
114 try:
Guido van Rossumd3876d31996-07-23 03:47:28 +0000115 st = os.lstat(path)
116 except (os.error, AttributeError):
Guido van Rossum7ac48781992-01-14 18:29:32 +0000117 return 0
118 return stat.S_ISLNK(st[stat.ST_MODE])
119
120
121# Does a path exist?
122# This is false for dangling symbolic links.
123
Guido van Rossumc6360141990-10-13 19:23:40 +0000124def exists(path):
125 try:
Guido van Rossumd3876d31996-07-23 03:47:28 +0000126 st = os.stat(path)
127 except os.error:
Guido van Rossumc6360141990-10-13 19:23:40 +0000128 return 0
129 return 1
130
131
Guido van Rossumd3876d31996-07-23 03:47:28 +0000132# Is a path a directory?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000133# This follows symbolic links, so both islink() and isdir() can be true
134# for the same path.
135
Guido van Rossumc6360141990-10-13 19:23:40 +0000136def isdir(path):
137 try:
Guido van Rossumd3876d31996-07-23 03:47:28 +0000138 st = os.stat(path)
139 except os.error:
Guido van Rossumc6360141990-10-13 19:23:40 +0000140 return 0
Guido van Rossum40d93041990-10-21 16:17:34 +0000141 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossumc6360141990-10-13 19:23:40 +0000142
143
Guido van Rossum26847381992-03-31 18:54:35 +0000144# Is a path a regular file?
Guido van Rossumb6775db1994-08-01 11:34:53 +0000145# This follows symbolic links, so both islink() and isfile() can be true
Guido van Rossum7ac48781992-01-14 18:29:32 +0000146# for the same path.
147
148def isfile(path):
Guido van Rossumc6360141990-10-13 19:23:40 +0000149 try:
Guido van Rossumd3876d31996-07-23 03:47:28 +0000150 st = os.stat(path)
151 except os.error:
Guido van Rossumc6360141990-10-13 19:23:40 +0000152 return 0
Guido van Rossum7ac48781992-01-14 18:29:32 +0000153 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossumc6360141990-10-13 19:23:40 +0000154
155
Guido van Rossumd3778f91991-11-12 15:37:40 +0000156# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000157
Guido van Rossumd3778f91991-11-12 15:37:40 +0000158def samefile(f1, f2):
Guido van Rossumd3876d31996-07-23 03:47:28 +0000159 s1 = os.stat(f1)
160 s2 = os.stat(f2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000161 return samestat(s1, s2)
162
163
164# Are two open files really referencing the same file?
165# (Not necessarily the same file descriptor!)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000166
Guido van Rossumd3778f91991-11-12 15:37:40 +0000167def sameopenfile(fp1, fp2):
Guido van Rossumd3876d31996-07-23 03:47:28 +0000168 s1 = os.fstat(fp1)
169 s2 = os.fstat(fp2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000170 return samestat(s1, s2)
171
172
173# Are two stat buffers (obtained from stat, fstat or lstat)
174# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000175
Guido van Rossumd3778f91991-11-12 15:37:40 +0000176def samestat(s1, s2):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000177 return s1[stat.ST_INO] == s2[stat.ST_INO] and \
Guido van Rossum509d24a1992-05-06 11:36:49 +0000178 s1[stat.ST_DEV] == s2[stat.ST_DEV]
Guido van Rossumc6360141990-10-13 19:23:40 +0000179
180
181# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000182# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000183
Guido van Rossumc6360141990-10-13 19:23:40 +0000184def ismount(path):
Guido van Rossum509d24a1992-05-06 11:36:49 +0000185 try:
Guido van Rossumd3876d31996-07-23 03:47:28 +0000186 s1 = os.stat(path)
187 s2 = os.stat(join(path, '..'))
188 except os.error:
Guido van Rossum509d24a1992-05-06 11:36:49 +0000189 return 0 # It doesn't exist -- so not a mount point :-)
190 dev1 = s1[stat.ST_DEV]
191 dev2 = s2[stat.ST_DEV]
192 if dev1 != dev2:
193 return 1 # path/.. on a different device as path
194 ino1 = s1[stat.ST_INO]
195 ino2 = s2[stat.ST_INO]
196 if ino1 == ino2:
197 return 1 # path/.. is the same i-node as path
198 return 0
Guido van Rossumc6360141990-10-13 19:23:40 +0000199
200
201# Directory tree walk.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000202# For each directory under top (including top itself, but excluding
203# '.' and '..'), func(arg, dirname, filenames) is called, where
204# dirname is the name of the directory and filenames is the list
205# files files (and subdirectories etc.) in the directory.
206# The func may modify the filenames list, to implement a filter,
Guido van Rossumc6360141990-10-13 19:23:40 +0000207# or to impose a different order of visiting.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000208
Guido van Rossumc6360141990-10-13 19:23:40 +0000209def walk(top, func, arg):
210 try:
Guido van Rossumd3876d31996-07-23 03:47:28 +0000211 names = os.listdir(top)
212 except os.error:
Guido van Rossumc6360141990-10-13 19:23:40 +0000213 return
214 func(arg, top, names)
215 exceptions = ('.', '..')
216 for name in names:
217 if name not in exceptions:
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000218 name = join(top, name)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000219 if isdir(name) and not islink(name):
Guido van Rossumc6360141990-10-13 19:23:40 +0000220 walk(name, func, arg)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000221
222
223# Expand paths beginning with '~' or '~user'.
224# '~' means $HOME; '~user' means that user's home directory.
225# If the path doesn't begin with '~', or if the user or $HOME is unknown,
226# the path is returned unchanged (leaving error reporting to whatever
227# function is called with the expanded path as argument).
228# See also module 'glob' for expansion of *, ? and [...] in pathnames.
229# (A function should also be defined to do full *sh-style environment
230# variable expansion.)
231
232def expanduser(path):
233 if path[:1] <> '~':
234 return path
235 i, n = 1, len(path)
236 while i < n and path[i] <> '/':
237 i = i+1
238 if i == 1:
Guido van Rossumd3876d31996-07-23 03:47:28 +0000239 if not os.environ.has_key('HOME'):
Guido van Rossum7ac48781992-01-14 18:29:32 +0000240 return path
Guido van Rossumd3876d31996-07-23 03:47:28 +0000241 userhome = os.environ['HOME']
Guido van Rossum7ac48781992-01-14 18:29:32 +0000242 else:
243 import pwd
244 try:
245 pwent = pwd.getpwnam(path[1:i])
246 except KeyError:
247 return path
248 userhome = pwent[5]
Guido van Rossumbbb4e101996-04-02 22:30:03 +0000249 if userhome[-1:] == '/': i = i+1
Guido van Rossum7ac48781992-01-14 18:29:32 +0000250 return userhome + path[i:]
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000251
252
253# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000254# This expands the forms $variable and ${variable} only.
255# Non-existant variables are left unchanged.
256
257_varprog = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000258
259def expandvars(path):
Guido van Rossumb6775db1994-08-01 11:34:53 +0000260 global _varprog
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000261 if '$' not in path:
262 return path
Guido van Rossumb6775db1994-08-01 11:34:53 +0000263 if not _varprog:
264 import regex
265 _varprog = regex.compile('$\([a-zA-Z0-9_]+\|{[^}]*}\)')
266 i = 0
267 while 1:
268 i = _varprog.search(path, i)
269 if i < 0:
270 break
271 name = _varprog.group(1)
272 j = i + len(_varprog.group(0))
273 if name[:1] == '{' and name[-1:] == '}':
274 name = name[1:-1]
Guido van Rossumd3876d31996-07-23 03:47:28 +0000275 if os.environ.has_key(name):
Guido van Rossumb6775db1994-08-01 11:34:53 +0000276 tail = path[j:]
Guido van Rossumd3876d31996-07-23 03:47:28 +0000277 path = path[:i] + os.environ[name]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000278 i = len(path)
279 path = path + tail
280 else:
281 i = j
282 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000283
284
285# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
286# It should be understood that this may change the meaning of the path
287# if it contains symbolic links!
288
289def normpath(path):
290 import string
Guido van Rossumdf563861993-07-06 15:19:36 +0000291 # Treat initial slashes specially
292 slashes = ''
293 while path[:1] == '/':
294 slashes = slashes + '/'
295 path = path[1:]
Guido van Rossumc629d341992-11-05 10:43:02 +0000296 comps = string.splitfields(path, '/')
Guido van Rossumc629d341992-11-05 10:43:02 +0000297 i = 0
298 while i < len(comps):
299 if comps[i] == '.':
300 del comps[i]
301 elif comps[i] == '..' and i > 0 and \
302 comps[i-1] not in ('', '..'):
303 del comps[i-1:i+1]
304 i = i-1
305 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
306 del comps[i]
307 else:
308 i = i+1
309 # If the path is now empty, substitute '.'
Guido van Rossumdf563861993-07-06 15:19:36 +0000310 if not comps and not slashes:
Guido van Rossumc629d341992-11-05 10:43:02 +0000311 comps.append('.')
Guido van Rossumdf563861993-07-06 15:19:36 +0000312 return slashes + string.joinfields(comps, '/')