posixpath.py 15 KB

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