home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_python.idb / usr / freeware / lib / python1.5 / ntpath.py.z / ntpath.py
Encoding:
Python Source  |  1999-04-16  |  11.8 KB  |  403 lines

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