1 # Module 'ntpath' -- common operations on WinNT/Win95 pathnames
2 """Common pathname manipulations, WindowsNT/95 version.
4 Instead of importing this module directly, import os and refer to this
13 # Normalize the case of a pathname and map slashes to backslashes.
14 # Other normalizations (such as optimizing '../' away) are not done
15 # (this is done by normpath).
18 """Normalize case of pathname.
20 Makes all characters lowercase and all slashes into backslashes."""
21 return string
.lower(string
.replace(s
, "/", "\\"))
24 # Return wheter a path is absolute.
25 # Trivial in Posix, harder on the Mac or MS-DOS.
26 # For DOS it is absolute if it starts with a slash or backslash (current
27 # volume), or if a pathname after the volume letter and colon / UNC resource
28 # starts with a slash or backslash.
31 """Test whether a path is absolute"""
33 return s
!= '' and s
[:1] in '/\\'
36 # Join two (or more) paths.
39 """Join two or more pathname components, inserting "\\" as needed"""
44 elif path
== '' or path
[-1:] in '/\\':
47 path
= path
+ os
.sep
+ b
51 # Split a path in a drive specification (a drive letter followed by a
52 # colon) and the path specification.
53 # It is always true that drivespec + pathspec == p
55 """Split a pathname into drive and path specifiers. Returns a 2-tuple
56 "(drive,path)"; either part may be empty"""
64 """Split a pathname into UNC mount point and relative path specifiers.
66 Return a 2-tuple (unc, rest); either part may be empty.
67 If unc is not empty, it has the form '//host/mount' (or similar
68 using backslashes). unc+rest is always the input path.
69 Paths containing drive letters never have an UNC part.
72 return '', p
# Drive letter present
74 if firstTwo
== '//' or firstTwo
== '\\\\':
76 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
77 # \\machine\mountpoint\directories...
78 # directory ^^^^^^^^^^^^^^^
80 index
= string
.find(normp
, '\\', 2)
82 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
84 index
= string
.find(normp
, '\\', index
+ 1)
87 return p
[:index
], p
[index
:]
91 # Split a path in head (everything up to the last '/') and tail (the
92 # rest). After the trailing '/' is stripped, the invariant
93 # join(head, tail) == p holds.
94 # The resulting head won't end in '/' unless it is the root.
99 Return tuple (head, tail) where tail is everything after the final slash.
100 Either part may be empty."""
103 # set i to index beyond p's last slash
105 while i
and p
[i
-1] not in '/\\':
107 head
, tail
= p
[:i
], p
[i
:] # now tail has no slashes
108 # remove trailing slashes from head, unless it's all slashes
110 while head2
and head2
[-1] in '/\\':
113 return d
+ head
, tail
116 # Split a path in root and extension.
117 # The extension is everything starting at the last dot in the last
118 # pathname component; the root is everything before that.
119 # It is always true that root + ext == p.
122 """Split the extension from a pathname.
124 Extension is everything from the last dot to the end.
125 Return (root, ext), either part may be empty."""
129 root
, ext
= root
+ ext
+ c
, ''
132 root
, ext
= root
+ ext
, c
142 # Return the tail (basename) part of a path.
145 """Returns the final component of a pathname"""
149 # Return the head (dirname) part of a path.
152 """Returns the directory component of a pathname"""
156 # Return the longest prefix of all list elements.
159 "Given a list of pathnames, returns the longest common leading component"
163 for i
in range(len(prefix
)):
164 if prefix
[:i
+1] <> item
[:i
+1]:
171 # Get size, mtime, atime of files.
173 def getsize(filename
):
174 """Return the size of a file, reported by os.stat()"""
175 st
= os
.stat(filename
)
176 return st
[stat
.ST_SIZE
]
178 def getmtime(filename
):
179 """Return the last modification time of a file, reported by os.stat()"""
180 st
= os
.stat(filename
)
181 return st
[stat
.ST_MTIME
]
183 def getatime(filename
):
184 """Return the last access time of a file, reported by os.stat()"""
185 st
= os
.stat(filename
)
186 return st
[stat
.ST_MTIME
]
189 # Is a path a symbolic link?
190 # This will always return false on systems where posix.lstat doesn't exist.
193 """Test for symbolic link. On WindowsNT/95 always returns false"""
198 # This is false for dangling symbolic links.
201 """Test whether a path exists"""
209 # Is a path a dos directory?
210 # This follows symbolic links, so both islink() and isdir() can be true
214 """Test whether a path is a directory"""
219 return stat
.S_ISDIR(st
[stat
.ST_MODE
])
222 # Is a path a regular file?
223 # This follows symbolic links, so both islink() and isdir() can be true
227 """Test whether a path is a regular file"""
232 return stat
.S_ISREG(st
[stat
.ST_MODE
])
235 # Is a path a mount point? Either a root (with or without drive letter)
236 # or an UNC path with at most a / or \ after the mount point.
239 """Test whether a path is a mount point (defined as root of drive)"""
240 unc
, rest
= splitunc(path
)
242 return rest
in ("", "/", "\\")
243 p
= splitdrive(path
)[1]
244 return len(p
)==1 and p
[0] in '/\\'
247 # Directory tree walk.
248 # For each directory under top (including top itself, but excluding
249 # '.' and '..'), func(arg, dirname, filenames) is called, where
250 # dirname is the name of the directory and filenames is the list
251 # files files (and subdirectories etc.) in the directory.
252 # The func may modify the filenames list, to implement a filter,
253 # or to impose a different order of visiting.
255 def walk(top
, func
, arg
):
256 """Directory tree walk whth callback function.
258 walk(top, func, arg) calls func(arg, d, files) for each directory d
259 in the tree rooted at top (including top itself); files is a list
260 of all the files and subdirs in directory d."""
262 names
= os
.listdir(top
)
265 func(arg
, top
, names
)
266 exceptions
= ('.', '..')
268 if name
not in exceptions
:
269 name
= join(top
, name
)
271 walk(name
, func
, arg
)
274 # Expand paths beginning with '~' or '~user'.
275 # '~' means $HOME; '~user' means that user's home directory.
276 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
277 # the path is returned unchanged (leaving error reporting to whatever
278 # function is called with the expanded path as argument).
279 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
280 # (A function should also be defined to do full *sh-style environment
281 # variable expansion.)
283 def expanduser(path
):
284 """Expand ~ and ~user constructs.
286 If user or $HOME is unknown, do nothing."""
290 while i
< n
and path
[i
] not in '/\\':
293 if os
.environ
.has_key('HOME'):
294 userhome
= os
.environ
['HOME']
295 elif not os
.environ
.has_key('HOMEPATH'):
299 drive
=os
.environ
['HOMEDRIVE']
302 userhome
= join(drive
, os
.environ
['HOMEPATH'])
305 return userhome
+ path
[i
:]
308 # Expand paths containing shell variable substitutions.
309 # The following rules apply:
310 # - no expansion within single quotes
311 # - no escape character, except for '$$' which is translated into '$'
312 # - ${varname} is accepted.
313 # - varnames can be made out of letters, digits and the character '_'
314 # XXX With COMMAND.COM you can use any characters in a variable name,
315 # XXX except '^|<>='.
317 varchars
= string
.letters
+ string
.digits
+ '_-'
319 def expandvars(path
):
320 """Expand shell variables of form $var and ${var}.
322 Unknown variables are left unchanged."""
328 while index
< pathlen
:
330 if c
== '\'': # no expansion within single quotes
331 path
= path
[index
+ 1:]
334 index
= string
.index(path
, '\'')
335 res
= res
+ '\'' + path
[:index
+ 1]
336 except string
.index_error
:
339 elif c
== '$': # variable or '$$'
340 if path
[index
+ 1:index
+ 2] == '$':
343 elif path
[index
+ 1:index
+ 2] == '{':
344 path
= path
[index
+2:]
347 index
= string
.index(path
, '}')
349 if os
.environ
.has_key(var
):
350 res
= res
+ os
.environ
[var
]
351 except string
.index_error
:
357 c
= path
[index
:index
+ 1]
358 while c
!= '' and c
in varchars
:
361 c
= path
[index
:index
+ 1]
362 if os
.environ
.has_key(var
):
363 res
= res
+ os
.environ
[var
]
372 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
373 # Previously, this function also truncated pathnames to 8+3 format,
374 # but as this module is called "ntpath", that's obviously wrong!
377 """Normalize path, eliminating double slashes, etc."""
378 path
= string
.replace(path
, "/", "\\")
379 prefix
, path
= splitdrive(path
)
380 while path
[:1] == os
.sep
:
381 prefix
= prefix
+ os
.sep
383 comps
= string
.splitfields(path
, os
.sep
)
385 while i
< len(comps
):
388 elif comps
[i
] == '..' and i
> 0 and comps
[i
-1] not in ('', '..'):
391 elif comps
[i
] == '' and i
> 0 and comps
[i
-1] <> '':
395 # If the path is now empty, substitute '.'
396 if not prefix
and not comps
:
398 return prefix
+ string
.joinfields(comps
, os
.sep
)
401 # Return an absolute path.
403 """Return the absolute version of a path"""
407 path
= win32api
.GetFullPathName(path
)
408 except win32api
.error
:
409 pass # Bad path - return unchanged.
412 path
= join(os
.getcwd(), path
)
413 return normpath(path
)