ntpath.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. # Module 'ntpath' -- common operations on WinNT/Win95 pathnames
  2. """Common pathname manipulations, WindowsNT/95 version.
  3. Instead of importing this module directly, import os and refer to this
  4. module as os.path.
  5. """
  6. import os
  7. import sys
  8. import stat
  9. import genericpath
  10. import warnings
  11. from genericpath import *
  12. from genericpath import _unicode
  13. __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
  14. "basename","dirname","commonprefix","getsize","getmtime",
  15. "getatime","getctime", "islink","exists","lexists","isdir","isfile",
  16. "ismount","walk","expanduser","expandvars","normpath","abspath",
  17. "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
  18. "extsep","devnull","realpath","supports_unicode_filenames","relpath"]
  19. # strings representing various path-related bits and pieces
  20. curdir = '.'
  21. pardir = '..'
  22. extsep = '.'
  23. sep = '\\'
  24. pathsep = ';'
  25. altsep = '/'
  26. defpath = '.;C:\\bin'
  27. if 'ce' in sys.builtin_module_names:
  28. defpath = '\\Windows'
  29. elif 'os2' in sys.builtin_module_names:
  30. # OS/2 w/ VACPP
  31. altsep = '/'
  32. devnull = 'nul'
  33. # Normalize the case of a pathname and map slashes to backslashes.
  34. # Other normalizations (such as optimizing '../' away) are not done
  35. # (this is done by normpath).
  36. def normcase(s):
  37. """Normalize case of pathname.
  38. Makes all characters lowercase and all slashes into backslashes."""
  39. return s.replace("/", "\\").lower()
  40. # Return whether a path is absolute.
  41. # Trivial in Posix, harder on the Mac or MS-DOS.
  42. # For DOS it is absolute if it starts with a slash or backslash (current
  43. # volume), or if a pathname after the volume letter and colon / UNC resource
  44. # starts with a slash or backslash.
  45. def isabs(s):
  46. """Test whether a path is absolute"""
  47. s = splitdrive(s)[1]
  48. return s != '' and s[:1] in '/\\'
  49. # Join two (or more) paths.
  50. def join(path, *paths):
  51. """Join two or more pathname components, inserting "\\" as needed."""
  52. result_drive, result_path = splitdrive(path)
  53. for p in paths:
  54. p_drive, p_path = splitdrive(p)
  55. if p_path and p_path[0] in '\\/':
  56. # Second path is absolute
  57. if p_drive or not result_drive:
  58. result_drive = p_drive
  59. result_path = p_path
  60. continue
  61. elif p_drive and p_drive != result_drive:
  62. if p_drive.lower() != result_drive.lower():
  63. # Different drives => ignore the first path entirely
  64. result_drive = p_drive
  65. result_path = p_path
  66. continue
  67. # Same drive in different case
  68. result_drive = p_drive
  69. # Second path is relative to the first
  70. if result_path and result_path[-1] not in '\\/':
  71. result_path = result_path + '\\'
  72. result_path = result_path + p_path
  73. ## add separator between UNC and non-absolute path
  74. if (result_path and result_path[0] not in '\\/' and
  75. result_drive and result_drive[-1:] != ':'):
  76. return result_drive + sep + result_path
  77. return result_drive + result_path
  78. # Split a path in a drive specification (a drive letter followed by a
  79. # colon) and the path specification.
  80. # It is always true that drivespec + pathspec == p
  81. def splitdrive(p):
  82. """Split a pathname into drive/UNC sharepoint and relative path specifiers.
  83. Returns a 2-tuple (drive_or_unc, path); either part may be empty.
  84. If you assign
  85. result = splitdrive(p)
  86. It is always true that:
  87. result[0] + result[1] == p
  88. If the path contained a drive letter, drive_or_unc will contain everything
  89. up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
  90. If the path contained a UNC path, the drive_or_unc will contain the host name
  91. and share up to but not including the fourth directory separator character.
  92. e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
  93. Paths cannot contain both a drive letter and a UNC path.
  94. """
  95. if len(p) > 1:
  96. normp = p.replace(altsep, sep)
  97. if (normp[0:2] == sep*2) and (normp[2:3] != sep):
  98. # is a UNC path:
  99. # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
  100. # \\machine\mountpoint\directory\etc\...
  101. # directory ^^^^^^^^^^^^^^^
  102. index = normp.find(sep, 2)
  103. if index == -1:
  104. return '', p
  105. index2 = normp.find(sep, index + 1)
  106. # a UNC path can't have two slashes in a row
  107. # (after the initial two)
  108. if index2 == index + 1:
  109. return '', p
  110. if index2 == -1:
  111. index2 = len(p)
  112. return p[:index2], p[index2:]
  113. if normp[1] == ':':
  114. return p[:2], p[2:]
  115. return '', p
  116. # Parse UNC paths
  117. def splitunc(p):
  118. """Split a pathname into UNC mount point and relative path specifiers.
  119. Return a 2-tuple (unc, rest); either part may be empty.
  120. If unc is not empty, it has the form '//host/mount' (or similar
  121. using backslashes). unc+rest is always the input path.
  122. Paths containing drive letters never have a UNC part.
  123. """
  124. if p[1:2] == ':':
  125. return '', p # Drive letter present
  126. firstTwo = p[0:2]
  127. if firstTwo == '//' or firstTwo == '\\\\':
  128. # is a UNC path:
  129. # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
  130. # \\machine\mountpoint\directories...
  131. # directory ^^^^^^^^^^^^^^^
  132. normp = p.replace('\\', '/')
  133. index = normp.find('/', 2)
  134. if index <= 2:
  135. return '', p
  136. index2 = normp.find('/', index + 1)
  137. # a UNC path can't have two slashes in a row
  138. # (after the initial two)
  139. if index2 == index + 1:
  140. return '', p
  141. if index2 == -1:
  142. index2 = len(p)
  143. return p[:index2], p[index2:]
  144. return '', p
  145. # Split a path in head (everything up to the last '/') and tail (the
  146. # rest). After the trailing '/' is stripped, the invariant
  147. # join(head, tail) == p holds.
  148. # The resulting head won't end in '/' unless it is the root.
  149. def split(p):
  150. """Split a pathname.
  151. Return tuple (head, tail) where tail is everything after the final slash.
  152. Either part may be empty."""
  153. d, p = splitdrive(p)
  154. # set i to index beyond p's last slash
  155. i = len(p)
  156. while i and p[i-1] not in '/\\':
  157. i = i - 1
  158. head, tail = p[:i], p[i:] # now tail has no slashes
  159. # remove trailing slashes from head, unless it's all slashes
  160. head2 = head
  161. while head2 and head2[-1] in '/\\':
  162. head2 = head2[:-1]
  163. head = head2 or head
  164. return d + head, tail
  165. # Split a path in root and extension.
  166. # The extension is everything starting at the last dot in the last
  167. # pathname component; the root is everything before that.
  168. # It is always true that root + ext == p.
  169. def splitext(p):
  170. return genericpath._splitext(p, sep, altsep, extsep)
  171. splitext.__doc__ = genericpath._splitext.__doc__
  172. # Return the tail (basename) part of a path.
  173. def basename(p):
  174. """Returns the final component of a pathname"""
  175. return split(p)[1]
  176. # Return the head (dirname) part of a path.
  177. def dirname(p):
  178. """Returns the directory component of a pathname"""
  179. return split(p)[0]
  180. # Is a path a symbolic link?
  181. # This will always return false on systems where posix.lstat doesn't exist.
  182. def islink(path):
  183. """Test for symbolic link.
  184. On WindowsNT/95 and OS/2 always returns false
  185. """
  186. return False
  187. # alias exists to lexists
  188. lexists = exists
  189. # Is a path a mount point? Either a root (with or without drive letter)
  190. # or a UNC path with at most a / or \ after the mount point.
  191. def ismount(path):
  192. """Test whether a path is a mount point (defined as root of drive)"""
  193. unc, rest = splitunc(path)
  194. if unc:
  195. return rest in ("", "/", "\\")
  196. p = splitdrive(path)[1]
  197. return len(p) == 1 and p[0] in '/\\'
  198. # Directory tree walk.
  199. # For each directory under top (including top itself, but excluding
  200. # '.' and '..'), func(arg, dirname, filenames) is called, where
  201. # dirname is the name of the directory and filenames is the list
  202. # of files (and subdirectories etc.) in the directory.
  203. # The func may modify the filenames list, to implement a filter,
  204. # or to impose a different order of visiting.
  205. def walk(top, func, arg):
  206. """Directory tree walk with callback function.
  207. For each directory in the directory tree rooted at top (including top
  208. itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
  209. dirname is the name of the directory, and fnames a list of the names of
  210. the files and subdirectories in dirname (excluding '.' and '..'). func
  211. may modify the fnames list in-place (e.g. via del or slice assignment),
  212. and walk will only recurse into the subdirectories whose names remain in
  213. fnames; this can be used to implement a filter, or to impose a specific
  214. order of visiting. No semantics are defined for, or required of, arg,
  215. beyond that arg is always passed to func. It can be used, e.g., to pass
  216. a filename pattern, or a mutable object designed to accumulate
  217. statistics. Passing None for arg is common."""
  218. warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",
  219. stacklevel=2)
  220. try:
  221. names = os.listdir(top)
  222. except os.error:
  223. return
  224. func(arg, top, names)
  225. for name in names:
  226. name = join(top, name)
  227. if isdir(name):
  228. walk(name, func, arg)
  229. # Expand paths beginning with '~' or '~user'.
  230. # '~' means $HOME; '~user' means that user's home directory.
  231. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  232. # the path is returned unchanged (leaving error reporting to whatever
  233. # function is called with the expanded path as argument).
  234. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  235. # (A function should also be defined to do full *sh-style environment
  236. # variable expansion.)
  237. def expanduser(path):
  238. """Expand ~ and ~user constructs.
  239. If user or $HOME is unknown, do nothing."""
  240. if path[:1] != '~':
  241. return path
  242. i, n = 1, len(path)
  243. while i < n and path[i] not in '/\\':
  244. i = i + 1
  245. if 'HOME' in os.environ:
  246. userhome = os.environ['HOME']
  247. elif 'USERPROFILE' in os.environ:
  248. userhome = os.environ['USERPROFILE']
  249. elif not 'HOMEPATH' in os.environ:
  250. return path
  251. else:
  252. try:
  253. drive = os.environ['HOMEDRIVE']
  254. except KeyError:
  255. drive = ''
  256. userhome = join(drive, os.environ['HOMEPATH'])
  257. if i != 1: #~user
  258. userhome = join(dirname(userhome), path[1:i])
  259. return userhome + path[i:]
  260. # Expand paths containing shell variable substitutions.
  261. # The following rules apply:
  262. # - no expansion within single quotes
  263. # - '$$' is translated into '$'
  264. # - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
  265. # - ${varname} is accepted.
  266. # - $varname is accepted.
  267. # - %varname% is accepted.
  268. # - varnames can be made out of letters, digits and the characters '_-'
  269. # (though is not verified in the ${varname} and %varname% cases)
  270. # XXX With COMMAND.COM you can use any characters in a variable name,
  271. # XXX except '^|<>='.
  272. def expandvars(path):
  273. """Expand shell variables of the forms $var, ${var} and %var%.
  274. Unknown variables are left unchanged."""
  275. if '$' not in path and '%' not in path:
  276. return path
  277. import string
  278. varchars = string.ascii_letters + string.digits + '_-'
  279. if isinstance(path, _unicode):
  280. encoding = sys.getfilesystemencoding()
  281. def getenv(var):
  282. return os.environ[var.encode(encoding)].decode(encoding)
  283. else:
  284. def getenv(var):
  285. return os.environ[var]
  286. res = ''
  287. index = 0
  288. pathlen = len(path)
  289. while index < pathlen:
  290. c = path[index]
  291. if c == '\'': # no expansion within single quotes
  292. path = path[index + 1:]
  293. pathlen = len(path)
  294. try:
  295. index = path.index('\'')
  296. res = res + '\'' + path[:index + 1]
  297. except ValueError:
  298. res = res + c + path
  299. index = pathlen - 1
  300. elif c == '%': # variable or '%'
  301. if path[index + 1:index + 2] == '%':
  302. res = res + c
  303. index = index + 1
  304. else:
  305. path = path[index+1:]
  306. pathlen = len(path)
  307. try:
  308. index = path.index('%')
  309. except ValueError:
  310. res = res + '%' + path
  311. index = pathlen - 1
  312. else:
  313. var = path[:index]
  314. try:
  315. res = res + getenv(var)
  316. except KeyError:
  317. res = res + '%' + var + '%'
  318. elif c == '$': # variable or '$$'
  319. if path[index + 1:index + 2] == '$':
  320. res = res + c
  321. index = index + 1
  322. elif path[index + 1:index + 2] == '{':
  323. path = path[index+2:]
  324. pathlen = len(path)
  325. try:
  326. index = path.index('}')
  327. var = path[:index]
  328. try:
  329. res = res + getenv(var)
  330. except KeyError:
  331. res = res + '${' + var + '}'
  332. except ValueError:
  333. res = res + '${' + path
  334. index = pathlen - 1
  335. else:
  336. var = ''
  337. index = index + 1
  338. c = path[index:index + 1]
  339. while c != '' and c in varchars:
  340. var = var + c
  341. index = index + 1
  342. c = path[index:index + 1]
  343. try:
  344. res = res + getenv(var)
  345. except KeyError:
  346. res = res + '$' + var
  347. if c != '':
  348. index = index - 1
  349. else:
  350. res = res + c
  351. index = index + 1
  352. return res
  353. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.
  354. # Previously, this function also truncated pathnames to 8+3 format,
  355. # but as this module is called "ntpath", that's obviously wrong!
  356. def normpath(path):
  357. """Normalize path, eliminating double slashes, etc."""
  358. # Preserve unicode (if path is unicode)
  359. backslash, dot = (u'\\', u'.') if isinstance(path, _unicode) else ('\\', '.')
  360. if path.startswith(('\\\\.\\', '\\\\?\\')):
  361. # in the case of paths with these prefixes:
  362. # \\.\ -> device names
  363. # \\?\ -> literal paths
  364. # do not do any normalization, but return the path unchanged
  365. return path
  366. path = path.replace("/", "\\")
  367. prefix, path = splitdrive(path)
  368. # We need to be careful here. If the prefix is empty, and the path starts
  369. # with a backslash, it could either be an absolute path on the current
  370. # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It
  371. # is therefore imperative NOT to collapse multiple backslashes blindly in
  372. # that case.
  373. # The code below preserves multiple backslashes when there is no drive
  374. # letter. This means that the invalid filename \\\a\b is preserved
  375. # unchanged, where a\\\b is normalised to a\b. It's not clear that there
  376. # is any better behaviour for such edge cases.
  377. if prefix == '':
  378. # No drive letter - preserve initial backslashes
  379. while path[:1] == "\\":
  380. prefix = prefix + backslash
  381. path = path[1:]
  382. else:
  383. # We have a drive letter - collapse initial backslashes
  384. if path.startswith("\\"):
  385. prefix = prefix + backslash
  386. path = path.lstrip("\\")
  387. comps = path.split("\\")
  388. i = 0
  389. while i < len(comps):
  390. if comps[i] in ('.', ''):
  391. del comps[i]
  392. elif comps[i] == '..':
  393. if i > 0 and comps[i-1] != '..':
  394. del comps[i-1:i+1]
  395. i -= 1
  396. elif i == 0 and prefix.endswith("\\"):
  397. del comps[i]
  398. else:
  399. i += 1
  400. else:
  401. i += 1
  402. # If the path is now empty, substitute '.'
  403. if not prefix and not comps:
  404. comps.append(dot)
  405. return prefix + backslash.join(comps)
  406. # Return an absolute path.
  407. try:
  408. from nt import _getfullpathname
  409. except ImportError: # not running on Windows - mock up something sensible
  410. def abspath(path):
  411. """Return the absolute version of a path."""
  412. if not isabs(path):
  413. if isinstance(path, _unicode):
  414. cwd = os.getcwdu()
  415. else:
  416. cwd = os.getcwd()
  417. path = join(cwd, path)
  418. return normpath(path)
  419. else: # use native Windows method on Windows
  420. def abspath(path):
  421. """Return the absolute version of a path."""
  422. if path: # Empty path must return current working directory.
  423. try:
  424. path = _getfullpathname(path)
  425. except WindowsError:
  426. pass # Bad path - return unchanged.
  427. elif isinstance(path, _unicode):
  428. path = os.getcwdu()
  429. else:
  430. path = os.getcwd()
  431. return normpath(path)
  432. # realpath is a no-op on systems without islink support
  433. realpath = abspath
  434. # Win9x family and earlier have no Unicode filename support.
  435. supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
  436. sys.getwindowsversion()[3] >= 2)
  437. def _abspath_split(path):
  438. abs = abspath(normpath(path))
  439. prefix, rest = splitunc(abs)
  440. is_unc = bool(prefix)
  441. if not is_unc:
  442. prefix, rest = splitdrive(abs)
  443. return is_unc, prefix, [x for x in rest.split(sep) if x]
  444. def relpath(path, start=curdir):
  445. """Return a relative version of a path"""
  446. if not path:
  447. raise ValueError("no path specified")
  448. start_is_unc, start_prefix, start_list = _abspath_split(start)
  449. path_is_unc, path_prefix, path_list = _abspath_split(path)
  450. if path_is_unc ^ start_is_unc:
  451. raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
  452. % (path, start))
  453. if path_prefix.lower() != start_prefix.lower():
  454. if path_is_unc:
  455. raise ValueError("path is on UNC root %s, start on UNC root %s"
  456. % (path_prefix, start_prefix))
  457. else:
  458. raise ValueError("path is on drive %s, start on drive %s"
  459. % (path_prefix, start_prefix))
  460. # Work out how much of the filepath is shared by start and path.
  461. i = 0
  462. for e1, e2 in zip(start_list, path_list):
  463. if e1.lower() != e2.lower():
  464. break
  465. i += 1
  466. rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
  467. if not rel_list:
  468. return curdir
  469. return join(*rel_list)
  470. try:
  471. # The genericpath.isdir implementation uses os.stat and checks the mode
  472. # attribute to tell whether or not the path is a directory.
  473. # This is overkill on Windows - just pass the path to GetFileAttributes
  474. # and check the attribute from there.
  475. from nt import _isdir as isdir
  476. except ImportError:
  477. # Use genericpath.isdir as imported above.
  478. pass