posixpath.py 15 KB

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