PageRenderTime 76ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/python/Lib/posixpath.py

https://github.com/hsablonniere/play
Python | 404 lines | 401 code | 0 blank | 3 comment | 0 complexity | d38ff07e283797a93085b258ab853733 MD5 | raw file
  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 stat
  12. import genericpath
  13. import warnings
  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","walk","expanduser","expandvars","normpath","abspath",
  19. "samefile","sameopenfile","samestat",
  20. "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
  21. "devnull","realpath","supports_unicode_filenames","relpath"]
  22. # strings representing various path-related bits and pieces
  23. curdir = '.'
  24. pardir = '..'
  25. extsep = '.'
  26. sep = '/'
  27. pathsep = ':'
  28. defpath = ':/bin:/usr/bin'
  29. altsep = None
  30. devnull = '/dev/null'
  31. # Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
  32. # On MS-DOS this may also turn slashes into backslashes; however, other
  33. # normalizations (such as optimizing '../' away) are not allowed
  34. # (another function should be defined to do that).
  35. def normcase(s):
  36. """Normalize case of pathname. Has no effect under Posix"""
  37. return s
  38. # Return whether a path is absolute.
  39. # Trivial in Posix, harder on the Mac or MS-DOS.
  40. def isabs(s):
  41. """Test whether a path is absolute"""
  42. return s.startswith('/')
  43. # Join pathnames.
  44. # Ignore the previous parts if a part is absolute.
  45. # Insert a '/' unless the first part is empty or already ends in '/'.
  46. def join(a, *p):
  47. """Join two or more pathname components, inserting '/' as needed.
  48. If any component is an absolute path, all previous path components
  49. will be discarded."""
  50. path = a
  51. for b in p:
  52. if b.startswith('/'):
  53. path = b
  54. elif path == '' or path.endswith('/'):
  55. path += b
  56. else:
  57. path += '/' + b
  58. return path
  59. # Split a path in head (everything up to the last '/') and tail (the
  60. # rest). If the path ends in '/', tail will be empty. If there is no
  61. # '/' in the path, head will be empty.
  62. # Trailing '/'es are stripped from head unless it is the root.
  63. def split(p):
  64. """Split a pathname. Returns tuple "(head, tail)" where "tail" is
  65. everything after the final slash. Either part may be empty."""
  66. i = p.rfind('/') + 1
  67. head, tail = p[:i], p[i:]
  68. if head and head != '/'*len(head):
  69. head = head.rstrip('/')
  70. return head, tail
  71. # Split a path in root and extension.
  72. # The extension is everything starting at the last dot in the last
  73. # pathname component; the root is everything before that.
  74. # It is always true that root + ext == p.
  75. def splitext(p):
  76. return genericpath._splitext(p, sep, altsep, extsep)
  77. splitext.__doc__ = genericpath._splitext.__doc__
  78. # Split a pathname into a drive specification and the rest of the
  79. # path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
  80. def splitdrive(p):
  81. """Split a pathname into drive and path. On Posix, drive is always
  82. empty."""
  83. return '', p
  84. # Return the tail (basename) part of a path, same as split(path)[1].
  85. def basename(p):
  86. """Returns the final component of a pathname"""
  87. i = p.rfind('/') + 1
  88. return p[i:]
  89. # Return the head (dirname) part of a path, same as split(path)[0].
  90. def dirname(p):
  91. """Returns the directory component of a pathname"""
  92. i = p.rfind('/') + 1
  93. head = p[:i]
  94. if head and head != '/'*len(head):
  95. head = head.rstrip('/')
  96. return head
  97. # Is a path a symbolic link?
  98. # This will always return false on systems where os.lstat doesn't exist.
  99. def islink(path):
  100. """Test whether a path is a symbolic link"""
  101. try:
  102. st = os.lstat(path)
  103. except (os.error, AttributeError):
  104. return False
  105. return stat.S_ISLNK(st.st_mode)
  106. # Being true for dangling symbolic links is also useful.
  107. def lexists(path):
  108. """Test whether a path exists. Returns True for broken symbolic links"""
  109. try:
  110. st = os.lstat(path)
  111. except os.error:
  112. return False
  113. return True
  114. # Are two filenames really pointing to the same file?
  115. def samefile(f1, f2):
  116. """Test whether two pathnames reference the same actual file"""
  117. s1 = os.stat(f1)
  118. s2 = os.stat(f2)
  119. return samestat(s1, s2)
  120. # Are two open files really referencing the same file?
  121. # (Not necessarily the same file descriptor!)
  122. def sameopenfile(fp1, fp2):
  123. """Test whether two open file objects reference the same file"""
  124. s1 = os.fstat(fp1)
  125. s2 = os.fstat(fp2)
  126. return samestat(s1, s2)
  127. # Are two stat buffers (obtained from stat, fstat or lstat)
  128. # describing the same file?
  129. def samestat(s1, s2):
  130. """Test whether two stat buffers reference the same file"""
  131. return s1.st_ino == s2.st_ino and \
  132. s1.st_dev == s2.st_dev
  133. # Is a path a mount point?
  134. # (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
  135. def ismount(path):
  136. """Test whether a path is a mount point"""
  137. try:
  138. s1 = os.lstat(path)
  139. s2 = os.lstat(join(path, '..'))
  140. except os.error:
  141. return False # It doesn't exist -- so not a mount point :-)
  142. dev1 = s1.st_dev
  143. dev2 = s2.st_dev
  144. if dev1 != dev2:
  145. return True # path/.. on a different device as path
  146. ino1 = s1.st_ino
  147. ino2 = s2.st_ino
  148. if ino1 == ino2:
  149. return True # path/.. is the same i-node as path
  150. return False
  151. # Directory tree walk.
  152. # For each directory under top (including top itself, but excluding
  153. # '.' and '..'), func(arg, dirname, filenames) is called, where
  154. # dirname is the name of the directory and filenames is the list
  155. # of files (and subdirectories etc.) in the directory.
  156. # The func may modify the filenames list, to implement a filter,
  157. # or to impose a different order of visiting.
  158. def walk(top, func, arg):
  159. """Directory tree walk with callback function.
  160. For each directory in the directory tree rooted at top (including top
  161. itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
  162. dirname is the name of the directory, and fnames a list of the names of
  163. the files and subdirectories in dirname (excluding '.' and '..'). func
  164. may modify the fnames list in-place (e.g. via del or slice assignment),
  165. and walk will only recurse into the subdirectories whose names remain in
  166. fnames; this can be used to implement a filter, or to impose a specific
  167. order of visiting. No semantics are defined for, or required of, arg,
  168. beyond that arg is always passed to func. It can be used, e.g., to pass
  169. a filename pattern, or a mutable object designed to accumulate
  170. statistics. Passing None for arg is common."""
  171. warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.")
  172. try:
  173. names = os.listdir(top)
  174. except os.error:
  175. return
  176. func(arg, top, names)
  177. for name in names:
  178. name = join(top, name)
  179. try:
  180. st = os.lstat(name)
  181. except os.error:
  182. continue
  183. if stat.S_ISDIR(st.st_mode):
  184. walk(name, func, arg)
  185. # Expand paths beginning with '~' or '~user'.
  186. # '~' means $HOME; '~user' means that user's home directory.
  187. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  188. # the path is returned unchanged (leaving error reporting to whatever
  189. # function is called with the expanded path as argument).
  190. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  191. # (A function should also be defined to do full *sh-style environment
  192. # variable expansion.)
  193. def expanduser(path):
  194. """Expand ~ and ~user constructions. If user or $HOME is unknown,
  195. do nothing."""
  196. if not path.startswith('~'):
  197. return path
  198. i = path.find('/', 1)
  199. if i < 0:
  200. i = len(path)
  201. if i == 1:
  202. if 'HOME' not in os.environ:
  203. import pwd
  204. userhome = pwd.getpwuid(os.getuid()).pw_dir
  205. else:
  206. userhome = os.environ['HOME']
  207. else:
  208. import pwd
  209. try:
  210. pwent = pwd.getpwnam(path[1:i])
  211. except KeyError:
  212. return path
  213. userhome = pwent.pw_dir
  214. userhome = userhome.rstrip('/')
  215. return userhome + path[i:]
  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. def expandvars(path):
  221. """Expand shell variables of form $var and ${var}. Unknown variables
  222. are left unchanged."""
  223. global _varprog
  224. if '$' not in path:
  225. return path
  226. if not _varprog:
  227. import re
  228. _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
  229. i = 0
  230. while True:
  231. m = _varprog.search(path, i)
  232. if not m:
  233. break
  234. i, j = m.span(0)
  235. name = m.group(1)
  236. if name.startswith('{') and name.endswith('}'):
  237. name = name[1:-1]
  238. if name in os.environ:
  239. tail = path[j:]
  240. path = path[:i] + os.environ[name]
  241. i = len(path)
  242. path += tail
  243. else:
  244. i = j
  245. return path
  246. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
  247. # It should be understood that this may change the meaning of the path
  248. # if it contains symbolic links!
  249. def normpath(path):
  250. """Normalize path, eliminating double slashes, etc."""
  251. if path == '':
  252. return '.'
  253. initial_slashes = path.startswith('/')
  254. # POSIX allows one or two initial slashes, but treats three or more
  255. # as single slash.
  256. if (initial_slashes and
  257. path.startswith('//') and not path.startswith('///')):
  258. initial_slashes = 2
  259. comps = path.split('/')
  260. new_comps = []
  261. for comp in comps:
  262. if comp in ('', '.'):
  263. continue
  264. if (comp != '..' or (not initial_slashes and not new_comps) or
  265. (new_comps and new_comps[-1] == '..')):
  266. new_comps.append(comp)
  267. elif new_comps:
  268. new_comps.pop()
  269. comps = new_comps
  270. path = '/'.join(comps)
  271. if initial_slashes:
  272. path = '/'*initial_slashes + path
  273. return path or '.'
  274. def abspath(path):
  275. """Return an absolute path."""
  276. if not isabs(path):
  277. path = join(os.getcwd(), path)
  278. return normpath(path)
  279. # Return a canonical path (i.e. the absolute location of a file on the
  280. # filesystem).
  281. def realpath(filename):
  282. """Return the canonical path of the specified filename, eliminating any
  283. symbolic links encountered in the path."""
  284. if isabs(filename):
  285. bits = ['/'] + filename.split('/')[1:]
  286. else:
  287. bits = [''] + filename.split('/')
  288. for i in range(2, len(bits)+1):
  289. component = join(*bits[0:i])
  290. # Resolve symbolic links.
  291. if islink(component):
  292. resolved = _resolve_link(component)
  293. if resolved is None:
  294. # Infinite loop -- return original component + rest of the path
  295. return abspath(join(*([component] + bits[i:])))
  296. else:
  297. newpath = join(*([resolved] + bits[i:]))
  298. return realpath(newpath)
  299. return abspath(filename)
  300. def _resolve_link(path):
  301. """Internal helper function. Takes a path and follows symlinks
  302. until we either arrive at something that isn't a symlink, or
  303. encounter a path we've seen before (meaning that there's a loop).
  304. """
  305. paths_seen = []
  306. while islink(path):
  307. if path in paths_seen:
  308. # Already seen this path, so we must have a symlink loop
  309. return None
  310. paths_seen.append(path)
  311. # Resolve where the link points to
  312. resolved = os.readlink(path)
  313. if not isabs(resolved):
  314. dir = dirname(path)
  315. path = normpath(join(dir, resolved))
  316. else:
  317. path = normpath(resolved)
  318. return path
  319. supports_unicode_filenames = False
  320. def relpath(path, start=curdir):
  321. """Return a relative version of a path"""
  322. if not path:
  323. raise ValueError("no path specified")
  324. start_list = abspath(start).split(sep)
  325. path_list = abspath(path).split(sep)
  326. # Work out how much of the filepath is shared by start and path.
  327. i = len(commonprefix([start_list, path_list]))
  328. rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
  329. if not rel_list:
  330. return curdir
  331. return join(*rel_list)