PageRenderTime 109ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/Python/system/posixpath.py

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