posixpath.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. """Common operations on Posix pathnames.
  2. Instead of importing this module directly, import os and refer to
  3. this module as os.path. The "os.path" name is an alias for this
  4. module on Posix systems; on other systems (e.g. Windows),
  5. os.path provides the same operations in a manner specific to that
  6. platform, and is an alias to another module (e.g. ntpath).
  7. Some of this can actually be useful on non-Posix systems too, e.g.
  8. for manipulation of the pathname component of URLs.
  9. """
  10. # Strings representing various path-related bits and pieces.
  11. # These are primarily for export; internally, they are hardcoded.
  12. # Should be set before imports for resolving cyclic dependency.
  13. curdir = '.'
  14. pardir = '..'
  15. extsep = '.'
  16. sep = '/'
  17. pathsep = ':'
  18. defpath = '/bin:/usr/bin'
  19. altsep = None
  20. devnull = '/dev/null'
  21. import os
  22. import sys
  23. import stat
  24. import genericpath
  25. from genericpath import *
  26. __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
  27. "basename","dirname","commonprefix","getsize","getmtime",
  28. "getatime","getctime","islink","exists","lexists","isdir","isfile",
  29. "ismount", "expanduser","expandvars","normpath","abspath",
  30. "samefile","sameopenfile","samestat",
  31. "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
  32. "devnull","realpath","supports_unicode_filenames","relpath",
  33. "commonpath"]
  34. def _get_sep(path):
  35. if isinstance(path, bytes):
  36. return b'/'
  37. else:
  38. return '/'
  39. # Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
  40. # On MS-DOS this may also turn slashes into backslashes; however, other
  41. # normalizations (such as optimizing '../' away) are not allowed
  42. # (another function should be defined to do that).
  43. def normcase(s):
  44. """Normalize case of pathname. Has no effect under Posix"""
  45. return os.fspath(s)
  46. # Return whether a path is absolute.
  47. # Trivial in Posix, harder on the Mac or MS-DOS.
  48. def isabs(s):
  49. """Test whether a path is absolute"""
  50. s = os.fspath(s)
  51. sep = _get_sep(s)
  52. return s.startswith(sep)
  53. # Join pathnames.
  54. # Ignore the previous parts if a part is absolute.
  55. # Insert a '/' unless the first part is empty or already ends in '/'.
  56. def join(a, *p):
  57. """Join two or more pathname components, inserting '/' as needed.
  58. If any component is an absolute path, all previous path components
  59. will be discarded. An empty last part will result in a path that
  60. ends with a separator."""
  61. a = os.fspath(a)
  62. sep = _get_sep(a)
  63. path = a
  64. try:
  65. if not p:
  66. path[:0] + sep #23780: Ensure compatible data type even if p is null.
  67. for b in map(os.fspath, p):
  68. if b.startswith(sep):
  69. path = b
  70. elif not path or path.endswith(sep):
  71. path += b
  72. else:
  73. path += sep + b
  74. except (TypeError, AttributeError, BytesWarning):
  75. genericpath._check_arg_types('join', a, *p)
  76. raise
  77. return path
  78. # Split a path in head (everything up to the last '/') and tail (the
  79. # rest). If the path ends in '/', tail will be empty. If there is no
  80. # '/' in the path, head will be empty.
  81. # Trailing '/'es are stripped from head unless it is the root.
  82. def split(p):
  83. """Split a pathname. Returns tuple "(head, tail)" where "tail" is
  84. everything after the final slash. Either part may be empty."""
  85. p = os.fspath(p)
  86. sep = _get_sep(p)
  87. i = p.rfind(sep) + 1
  88. head, tail = p[:i], p[i:]
  89. if head and head != sep*len(head):
  90. head = head.rstrip(sep)
  91. return head, tail
  92. # Split a path in root and extension.
  93. # The extension is everything starting at the last dot in the last
  94. # pathname component; the root is everything before that.
  95. # It is always true that root + ext == p.
  96. def splitext(p):
  97. p = os.fspath(p)
  98. if isinstance(p, bytes):
  99. sep = b'/'
  100. extsep = b'.'
  101. else:
  102. sep = '/'
  103. extsep = '.'
  104. return genericpath._splitext(p, sep, None, extsep)
  105. splitext.__doc__ = genericpath._splitext.__doc__
  106. # Split a pathname into a drive specification and the rest of the
  107. # path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
  108. def splitdrive(p):
  109. """Split a pathname into drive and path. On Posix, drive is always
  110. empty."""
  111. p = os.fspath(p)
  112. return p[:0], p
  113. # Return the tail (basename) part of a path, same as split(path)[1].
  114. def basename(p):
  115. """Returns the final component of a pathname"""
  116. p = os.fspath(p)
  117. sep = _get_sep(p)
  118. i = p.rfind(sep) + 1
  119. return p[i:]
  120. # Return the head (dirname) part of a path, same as split(path)[0].
  121. def dirname(p):
  122. """Returns the directory component of a pathname"""
  123. p = os.fspath(p)
  124. sep = _get_sep(p)
  125. i = p.rfind(sep) + 1
  126. head = p[:i]
  127. if head and head != sep*len(head):
  128. head = head.rstrip(sep)
  129. return head
  130. # Is a path a symbolic link?
  131. # This will always return false on systems where os.lstat doesn't exist.
  132. def islink(path):
  133. """Test whether a path is a symbolic link"""
  134. try:
  135. st = os.lstat(path)
  136. except (OSError, ValueError, AttributeError):
  137. return False
  138. return stat.S_ISLNK(st.st_mode)
  139. # Being true for dangling symbolic links is also useful.
  140. def lexists(path):
  141. """Test whether a path exists. Returns True for broken symbolic links"""
  142. try:
  143. os.lstat(path)
  144. except (OSError, ValueError):
  145. return False
  146. return True
  147. # Is a path a mount point?
  148. # (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
  149. def ismount(path):
  150. """Test whether a path is a mount point"""
  151. try:
  152. s1 = os.lstat(path)
  153. except (OSError, ValueError):
  154. # It doesn't exist -- so not a mount point. :-)
  155. return False
  156. else:
  157. # A symlink can never be a mount point
  158. if stat.S_ISLNK(s1.st_mode):
  159. return False
  160. if isinstance(path, bytes):
  161. parent = join(path, b'..')
  162. else:
  163. parent = join(path, '..')
  164. parent = realpath(parent)
  165. try:
  166. s2 = os.lstat(parent)
  167. except (OSError, ValueError):
  168. return False
  169. dev1 = s1.st_dev
  170. dev2 = s2.st_dev
  171. if dev1 != dev2:
  172. return True # path/.. on a different device as path
  173. ino1 = s1.st_ino
  174. ino2 = s2.st_ino
  175. if ino1 == ino2:
  176. return True # path/.. is the same i-node as path
  177. return False
  178. # Expand paths beginning with '~' or '~user'.
  179. # '~' means $HOME; '~user' means that user's home directory.
  180. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  181. # the path is returned unchanged (leaving error reporting to whatever
  182. # function is called with the expanded path as argument).
  183. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  184. # (A function should also be defined to do full *sh-style environment
  185. # variable expansion.)
  186. def expanduser(path):
  187. """Expand ~ and ~user constructions. If user or $HOME is unknown,
  188. do nothing."""
  189. path = os.fspath(path)
  190. if isinstance(path, bytes):
  191. tilde = b'~'
  192. else:
  193. tilde = '~'
  194. if not path.startswith(tilde):
  195. return path
  196. sep = _get_sep(path)
  197. i = path.find(sep, 1)
  198. if i < 0:
  199. i = len(path)
  200. if i == 1:
  201. if 'HOME' not in os.environ:
  202. import pwd
  203. try:
  204. userhome = pwd.getpwuid(os.getuid()).pw_dir
  205. except KeyError:
  206. # bpo-10496: if the current user identifier doesn't exist in the
  207. # password database, return the path unchanged
  208. return path
  209. else:
  210. userhome = os.environ['HOME']
  211. else:
  212. import pwd
  213. name = path[1:i]
  214. if isinstance(name, bytes):
  215. name = str(name, 'ASCII')
  216. try:
  217. pwent = pwd.getpwnam(name)
  218. except KeyError:
  219. # bpo-10496: if the user name from the path doesn't exist in the
  220. # password database, return the path unchanged
  221. return path
  222. userhome = pwent.pw_dir
  223. if isinstance(path, bytes):
  224. userhome = os.fsencode(userhome)
  225. root = b'/'
  226. else:
  227. root = '/'
  228. userhome = userhome.rstrip(root)
  229. return (userhome + path[i:]) or root
  230. # Expand paths containing shell variable substitutions.
  231. # This expands the forms $variable and ${variable} only.
  232. # Non-existent variables are left unchanged.
  233. _varprog = None
  234. _varprogb = None
  235. def expandvars(path):
  236. """Expand shell variables of form $var and ${var}. Unknown variables
  237. are left unchanged."""
  238. path = os.fspath(path)
  239. global _varprog, _varprogb
  240. if isinstance(path, bytes):
  241. if b'$' not in path:
  242. return path
  243. if not _varprogb:
  244. import re
  245. _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII)
  246. search = _varprogb.search
  247. start = b'{'
  248. end = b'}'
  249. environ = getattr(os, 'environb', None)
  250. else:
  251. if '$' not in path:
  252. return path
  253. if not _varprog:
  254. import re
  255. _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
  256. search = _varprog.search
  257. start = '{'
  258. end = '}'
  259. environ = os.environ
  260. i = 0
  261. while True:
  262. m = search(path, i)
  263. if not m:
  264. break
  265. i, j = m.span(0)
  266. name = m.group(1)
  267. if name.startswith(start) and name.endswith(end):
  268. name = name[1:-1]
  269. try:
  270. if environ is None:
  271. value = os.fsencode(os.environ[os.fsdecode(name)])
  272. else:
  273. value = environ[name]
  274. except KeyError:
  275. i = j
  276. else:
  277. tail = path[j:]
  278. path = path[:i] + value
  279. i = len(path)
  280. path += tail
  281. return path
  282. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
  283. # It should be understood that this may change the meaning of the path
  284. # if it contains symbolic links!
  285. def normpath(path):
  286. """Normalize path, eliminating double slashes, etc."""
  287. path = os.fspath(path)
  288. if isinstance(path, bytes):
  289. sep = b'/'
  290. empty = b''
  291. dot = b'.'
  292. dotdot = b'..'
  293. else:
  294. sep = '/'
  295. empty = ''
  296. dot = '.'
  297. dotdot = '..'
  298. if path == empty:
  299. return dot
  300. initial_slashes = path.startswith(sep)
  301. # POSIX allows one or two initial slashes, but treats three or more
  302. # as single slash.
  303. # (see http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13)
  304. if (initial_slashes and
  305. path.startswith(sep*2) and not path.startswith(sep*3)):
  306. initial_slashes = 2
  307. comps = path.split(sep)
  308. new_comps = []
  309. for comp in comps:
  310. if comp in (empty, dot):
  311. continue
  312. if (comp != dotdot or (not initial_slashes and not new_comps) or
  313. (new_comps and new_comps[-1] == dotdot)):
  314. new_comps.append(comp)
  315. elif new_comps:
  316. new_comps.pop()
  317. comps = new_comps
  318. path = sep.join(comps)
  319. if initial_slashes:
  320. path = sep*initial_slashes + path
  321. return path or dot
  322. def abspath(path):
  323. """Return an absolute path."""
  324. path = os.fspath(path)
  325. if not isabs(path):
  326. if isinstance(path, bytes):
  327. cwd = os.getcwdb()
  328. else:
  329. cwd = os.getcwd()
  330. path = join(cwd, path)
  331. return normpath(path)
  332. # Return a canonical path (i.e. the absolute location of a file on the
  333. # filesystem).
  334. def realpath(filename):
  335. """Return the canonical path of the specified filename, eliminating any
  336. symbolic links encountered in the path."""
  337. filename = os.fspath(filename)
  338. path, ok = _joinrealpath(filename[:0], filename, {})
  339. return abspath(path)
  340. # Join two paths, normalizing and eliminating any symbolic links
  341. # encountered in the second path.
  342. def _joinrealpath(path, rest, seen):
  343. if isinstance(path, bytes):
  344. sep = b'/'
  345. curdir = b'.'
  346. pardir = b'..'
  347. else:
  348. sep = '/'
  349. curdir = '.'
  350. pardir = '..'
  351. if isabs(rest):
  352. rest = rest[1:]
  353. path = sep
  354. while rest:
  355. name, _, rest = rest.partition(sep)
  356. if not name or name == curdir:
  357. # current dir
  358. continue
  359. if name == pardir:
  360. # parent dir
  361. if path:
  362. path, name = split(path)
  363. if name == pardir:
  364. path = join(path, pardir, pardir)
  365. else:
  366. path = pardir
  367. continue
  368. newpath = join(path, name)
  369. if not islink(newpath):
  370. path = newpath
  371. continue
  372. # Resolve the symbolic link
  373. if newpath in seen:
  374. # Already seen this path
  375. path = seen[newpath]
  376. if path is not None:
  377. # use cached value
  378. continue
  379. # The symlink is not resolved, so we must have a symlink loop.
  380. # Return already resolved part + rest of the path unchanged.
  381. return join(newpath, rest), False
  382. seen[newpath] = None # not resolved symlink
  383. path, ok = _joinrealpath(path, os.readlink(newpath), seen)
  384. if not ok:
  385. return join(path, rest), False
  386. seen[newpath] = path # resolved symlink
  387. return path, True
  388. supports_unicode_filenames = (sys.platform == 'darwin')
  389. def relpath(path, start=None):
  390. """Return a relative version of a path"""
  391. if not path:
  392. raise ValueError("no path specified")
  393. path = os.fspath(path)
  394. if isinstance(path, bytes):
  395. curdir = b'.'
  396. sep = b'/'
  397. pardir = b'..'
  398. else:
  399. curdir = '.'
  400. sep = '/'
  401. pardir = '..'
  402. if start is None:
  403. start = curdir
  404. else:
  405. start = os.fspath(start)
  406. try:
  407. start_list = [x for x in abspath(start).split(sep) if x]
  408. path_list = [x for x in abspath(path).split(sep) if x]
  409. # Work out how much of the filepath is shared by start and path.
  410. i = len(commonprefix([start_list, path_list]))
  411. rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
  412. if not rel_list:
  413. return curdir
  414. return join(*rel_list)
  415. except (TypeError, AttributeError, BytesWarning, DeprecationWarning):
  416. genericpath._check_arg_types('relpath', path, start)
  417. raise
  418. # Return the longest common sub-path of the sequence of paths given as input.
  419. # The paths are not normalized before comparing them (this is the
  420. # responsibility of the caller). Any trailing separator is stripped from the
  421. # returned path.
  422. def commonpath(paths):
  423. """Given a sequence of path names, returns the longest common sub-path."""
  424. if not paths:
  425. raise ValueError('commonpath() arg is an empty sequence')
  426. paths = tuple(map(os.fspath, paths))
  427. if isinstance(paths[0], bytes):
  428. sep = b'/'
  429. curdir = b'.'
  430. else:
  431. sep = '/'
  432. curdir = '.'
  433. try:
  434. split_paths = [path.split(sep) for path in paths]
  435. try:
  436. isabs, = set(p[:1] == sep for p in paths)
  437. except ValueError:
  438. raise ValueError("Can't mix absolute and relative paths") from None
  439. split_paths = [[c for c in s if c and c != curdir] for s in split_paths]
  440. s1 = min(split_paths)
  441. s2 = max(split_paths)
  442. common = s1
  443. for i, c in enumerate(s1):
  444. if c != s2[i]:
  445. common = s1[:i]
  446. break
  447. prefix = sep if isabs else sep[:0]
  448. return prefix + sep.join(common)
  449. except (TypeError, AttributeError):
  450. genericpath._check_arg_types('commonpath', *paths)
  451. raise