home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / ntpath.py < prev    next >
Text File  |  1997-12-05  |  11KB  |  379 lines

  1. # Module 'ntpath' -- common operations on WinNT/Win95 pathnames
  2. """Common pathname manipulations, WindowsNT/95 version. 
  3. Instead of importing this module
  4. directly, import os and refer to this module as os.path.
  5. """
  6.  
  7. import os
  8. import stat
  9. import string
  10.  
  11.  
  12. # Normalize the case of a pathname and map slashes to backslashes.
  13. # Other normalizations (such as optimizing '../' away) are not done
  14. # (this is done by normpath).
  15.  
  16. _normtable = string.maketrans(string.uppercase + "\\/",
  17.                               string.lowercase + os.sep * 2)
  18.  
  19. def normcase(s):
  20.     """Normalize case of pathname.  Makes all characters lowercase and all 
  21. slashes into backslashes"""
  22.     return string.translate(s, _normtable)
  23.  
  24.  
  25. # Return wheter a path is absolute.
  26. # Trivial in Posix, harder on the Mac or MS-DOS.
  27. # For DOS it is absolute if it starts with a slash or backslash (current
  28. # volume), or if a pathname after the volume letter and colon starts with
  29. # a slash or backslash.
  30.  
  31. def isabs(s):
  32.     """Test whether a path is absolute"""
  33.     s = splitdrive(s)[1]
  34.     return s != '' and s[:1] in '/\\'
  35.  
  36.  
  37. # Join two (or more) paths.
  38.  
  39. def join(a, *p):
  40.     """Join two or more pathname components, inserting "\\" as needed"""
  41.     path = a
  42.     for b in p:
  43.         if isabs(b):
  44.             path = b
  45.         elif path == '' or path[-1:] in '/\\':
  46.             path = path + b
  47.         else:
  48.             path = path + os.sep + b
  49.     return path
  50.  
  51.  
  52. # Split a path in a drive specification (a drive letter followed by a
  53. # colon) and the path specification.
  54. # It is always true that drivespec + pathspec == p
  55. def splitdrive(p):
  56.     """Split a pathname into drive and path specifiers. Returns a 2-tuple
  57. "(drive,path)";  either part may be empty"""
  58.     if p[1:2] == ':':
  59.         return p[0:2], p[2:]
  60.     return '', p
  61.  
  62.  
  63. # Split a path in head (everything up to the last '/') and tail (the
  64. # rest).  If the original path ends in '/' but is not the root, this
  65. # '/' is stripped.  After the trailing '/' is stripped, the invariant
  66. # join(head, tail) == p holds.
  67. # The resulting head won't end in '/' unless it is the root.
  68.  
  69. def split(p):
  70.     """Split a pathname.  Returns tuple "(head, tail)" where "tail" is 
  71. everything after the final slash.  Either part may be empty"""
  72.     d, p = splitdrive(p)
  73.     slashes = ''
  74.     while p and p[-1:] in '/\\':
  75.         slashes = slashes + p[-1]
  76.         p = p[:-1]
  77.     if p == '':
  78.         p = p + slashes
  79.     head, tail = '', ''
  80.     for c in p:
  81.         tail = tail + c
  82.         if c in '/\\':
  83.             head, tail = head + tail, ''
  84.     slashes = ''
  85.     while head and head[-1:] in '/\\':
  86.         slashes = slashes + head[-1]
  87.         head = head[:-1]
  88.     if head == '':
  89.         head = head + slashes
  90.     return d + head, tail
  91.  
  92.  
  93. # Split a path in root and extension.
  94. # The extension is everything starting at the last dot in the last
  95. # pathname component; the root is everything before that.
  96. # It is always true that root + ext == p.
  97.  
  98. def splitext(p):
  99.     """Split the extension from a pathname.  Extension is everything from the
  100. last dot to the end.  Returns "(root, ext)", either part may be empty"""
  101.     root, ext = '', ''
  102.     for c in p:
  103.         if c in ['/','\\']:
  104.             root, ext = root + ext + c, ''
  105.         elif c == '.':
  106.             if ext:
  107.                 root, ext = root + ext, c
  108.             else:
  109.                 ext = c
  110.         elif ext:
  111.             ext = ext + c
  112.         else:
  113.             root = root + c
  114.     return root, ext
  115.  
  116.  
  117. # Return the tail (basename) part of a path.
  118.  
  119. def basename(p):
  120.     """Returns the final component of a pathname"""
  121.     return split(p)[1]
  122.  
  123.  
  124. # Return the head (dirname) part of a path.
  125.  
  126. def dirname(p):
  127.     """Returns the directory component of a pathname"""
  128.     return split(p)[0]
  129.  
  130.  
  131. # Return the longest prefix of all list elements.
  132.  
  133. def commonprefix(m):
  134.     "Given a list of pathnames, returns the longest common leading component"
  135.     if not m: return ''
  136.     prefix = m[0]
  137.     for item in m:
  138.         for i in range(len(prefix)):
  139.             if prefix[:i+1] <> item[:i+1]:
  140.                 prefix = prefix[:i]
  141.                 if i == 0: return ''
  142.                 break
  143.     return prefix
  144.  
  145.  
  146. # Is a path a symbolic link?
  147. # This will always return false on systems where posix.lstat doesn't exist.
  148.  
  149. def islink(path):
  150.     """Test for symbolic link.  On WindowsNT/95 always returns false"""
  151.     return 0
  152.  
  153.  
  154. # Does a path exist?
  155. # This is false for dangling symbolic links.
  156.  
  157. def exists(path):
  158.     """Test whether a path exists"""
  159.     try:
  160.         st = os.stat(path)
  161.     except os.error:
  162.         return 0
  163.     return 1
  164.  
  165.  
  166. # Is a path a dos directory?
  167. # This follows symbolic links, so both islink() and isdir() can be true
  168. # for the same path.
  169.  
  170. def isdir(path):
  171.     """Test whether a path is a directory"""
  172.     try:
  173.         st = os.stat(path)
  174.     except os.error:
  175.         return 0
  176.     return stat.S_ISDIR(st[stat.ST_MODE])
  177.  
  178.  
  179. # Is a path a regular file?
  180. # This follows symbolic links, so both islink() and isdir() can be true
  181. # for the same path.
  182.  
  183. def isfile(path):
  184.     """Test whether a path is a regular file"""
  185.     try:
  186.         st = os.stat(path)
  187.     except os.error:
  188.         return 0
  189.     return stat.S_ISREG(st[stat.ST_MODE])
  190.  
  191.  
  192. # Are two filenames really pointing to the same file?
  193.  
  194. def samefile(f1, f2):
  195.     """Test whether two pathnames reference the same actual file"""
  196.     s1 = os.stat(f1)
  197.     s2 = os.stat(f2)
  198.     return samestat(s1, s2)
  199.  
  200.  
  201. # Are two open files really referencing the same file?
  202. # (Not necessarily the same file descriptor!)
  203. # XXX THIS IS BROKEN UNDER DOS! ST_INO seems to indicate number of reads?
  204.  
  205. def sameopenfile(fp1, fp2):
  206.     """Test whether two open file objects reference the same file (may not
  207. work correctly)"""
  208.     s1 = os.fstat(fp1.fileno())
  209.     s2 = os.fstat(fp2.fileno())
  210.     return samestat(s1, s2)
  211.  
  212.  
  213. # Are two stat buffers (obtained from stat, fstat or lstat)
  214. # describing the same file?
  215.  
  216. def samestat(s1, s2):
  217.     """Test whether two stat buffers reference the same file"""
  218.     return s1[stat.ST_INO] == s2[stat.ST_INO] and \
  219.            s1[stat.ST_DEV] == s2[stat.ST_DEV]
  220.  
  221.  
  222. # Is a path a mount point?
  223. # XXX This degenerates in: 'is this the root?' on DOS
  224.  
  225. def ismount(path):
  226.     """Test whether a path is a mount point"""
  227.     return isabs(splitdrive(path)[1])
  228.  
  229.  
  230. # Directory tree walk.
  231. # For each directory under top (including top itself, but excluding
  232. # '.' and '..'), func(arg, dirname, filenames) is called, where
  233. # dirname is the name of the directory and filenames is the list
  234. # files files (and subdirectories etc.) in the directory.
  235. # The func may modify the filenames list, to implement a filter,
  236. # or to impose a different order of visiting.
  237.  
  238. def walk(top, func, arg):
  239.     """walk(top,func,args) calls func(arg, d, files) for each directory "d" 
  240. in the tree  rooted at "top" (including "top" itself).  "files" is a list
  241. of all the files and subdirs in directory "d".
  242. """
  243.     try:
  244.         names = os.listdir(top)
  245.     except os.error:
  246.         return
  247.     func(arg, top, names)
  248.     exceptions = ('.', '..')
  249.     for name in names:
  250.         if name not in exceptions:
  251.             name = join(top, name)
  252.             if isdir(name):
  253.                 walk(name, func, arg)
  254.  
  255.  
  256. # Expand paths beginning with '~' or '~user'.
  257. # '~' means $HOME; '~user' means that user's home directory.
  258. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  259. # the path is returned unchanged (leaving error reporting to whatever
  260. # function is called with the expanded path as argument).
  261. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  262. # (A function should also be defined to do full *sh-style environment
  263. # variable expansion.)
  264.  
  265. def expanduser(path):
  266.     """Expand ~ and ~user constructions.  If user or $HOME is unknown, 
  267. do nothing"""
  268.     if path[:1] <> '~':
  269.         return path
  270.     i, n = 1, len(path)
  271.     while i < n and path[i] not in '/\\':
  272.         i = i+1
  273.     if i == 1:
  274.         if os.environ.has_key('HOME'):
  275.             userhome = os.environ['HOME']
  276.         elif not os.environ.has_key('HOMEPATH'):
  277.             return path
  278.         else:
  279.             try:
  280.                 drive=os.environ['HOMEDRIVE']
  281.             except KeyError:
  282.                 drive = ''
  283.             userhome = join(drive, os.environ['HOMEPATH'])
  284.     else:
  285.         return path
  286.     return userhome + path[i:]
  287.  
  288.  
  289. # Expand paths containing shell variable substitutions.
  290. # The following rules apply:
  291. #       - no expansion within single quotes
  292. #       - no escape character, except for '$$' which is translated into '$'
  293. #       - ${varname} is accepted.
  294. #       - varnames can be made out of letters, digits and the character '_'
  295. # XXX With COMMAND.COM you can use any characters in a variable name,
  296. # XXX except '^|<>='.
  297.  
  298. varchars = string.letters + string.digits + '_-'
  299.  
  300. def expandvars(path):  
  301.     """Expand shell variables of form $var and ${var}.  Unknown variables
  302. are left unchanged"""
  303.     if '$' not in path:
  304.         return path
  305.     res = ''
  306.     index = 0
  307.     pathlen = len(path)
  308.     while index < pathlen:
  309.         c = path[index]
  310.         if c == '\'':   # no expansion within single quotes
  311.             path = path[index + 1:]
  312.             pathlen = len(path)
  313.             try:
  314.                 index = string.index(path, '\'')
  315.                 res = res + '\'' + path[:index + 1]
  316.             except string.index_error:
  317.                 res = res + path
  318.                 index = pathlen -1
  319.         elif c == '$':  # variable or '$$'
  320.             if path[index + 1:index + 2] == '$':
  321.                 res = res + c
  322.                 index = index + 1
  323.             elif path[index + 1:index + 2] == '{':
  324.                 path = path[index+2:]
  325.                 pathlen = len(path)
  326.                 try:
  327.                     index = string.index(path, '}')
  328.                     var = path[:index]
  329.                     if os.environ.has_key(var):
  330.                         res = res + os.environ[var]
  331.                 except string.index_error:
  332.                     res = res + path
  333.                     index = pathlen - 1
  334.             else:
  335.                 var = ''
  336.                 index = index + 1
  337.                 c = path[index:index + 1]
  338.                 while c != '' and c in varchars:
  339.                     var = var + c
  340.                     index = index + 1
  341.                     c = path[index:index + 1]
  342.                 if os.environ.has_key(var):
  343.                     res = res + os.environ[var]
  344.                 if c != '':
  345.                     res = res + c
  346.         else:
  347.             res = res + c
  348.         index = index + 1
  349.     return res
  350.  
  351.  
  352. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
  353. # Previously, this function also truncated pathnames to 8+3 format,
  354. # but as this module is called "ntpath", that's obviously wrong!
  355.  
  356. def normpath(path):
  357.     """Normalize path, eliminating double slashes, etc."""
  358.     path = normcase(path)
  359.     prefix, path = splitdrive(path)
  360.     while path[:1] == os.sep:
  361.         prefix = prefix + os.sep
  362.         path = path[1:]
  363.     comps = string.splitfields(path, os.sep)
  364.     i = 0
  365.     while i < len(comps):
  366.         if comps[i] == '.':
  367.             del comps[i]
  368.         elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
  369.             del comps[i-1:i+1]
  370.             i = i-1
  371.         elif comps[i] == '' and i > 0 and comps[i-1] <> '':
  372.             del comps[i]
  373.         else:
  374.             i = i+1
  375.     # If the path is now empty, substitute '.'
  376.     if not prefix and not comps:
  377.         comps.append('.')
  378.     return prefix + string.joinfields(comps, os.sep)
  379.