home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_Lib_dospath.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  9.7 KB  |  333 lines

  1. """Common operations on DOS pathnames."""
  2.  
  3. import os
  4. import stat
  5.  
  6. __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
  7.            "basename","dirname","commonprefix","getsize","getmtime",
  8.            "getatime","islink","exists","isdir","isfile","ismount",
  9.            "walk","expanduser","expandvars","normpath","abspath"]
  10.  
  11. def normcase(s):
  12.     """Normalize the case of a pathname.
  13.     On MS-DOS it maps the pathname to lowercase, turns slashes into
  14.     backslashes.
  15.     Other normalizations (such as optimizing '../' away) are not allowed
  16.     (this is done by normpath).
  17.     Previously, this version mapped invalid consecutive characters to a
  18.     single '_', but this has been removed.  This functionality should
  19.     possibly be added as a new function."""
  20.  
  21.     return s.replace("/", "\\").lower()
  22.  
  23.  
  24. def isabs(s):
  25.     """Return whether 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.     s = splitdrive(s)[1]
  32.     return s != '' and s[:1] in '/\\'
  33.  
  34.  
  35. def join(a, *p):
  36.     """Join two (or more) paths."""
  37.  
  38.     path = a
  39.     for b in p:
  40.         if isabs(b):
  41.             path = b
  42.         elif path == '' or path[-1:] in '/\\:':
  43.             path = path + b
  44.         else:
  45.             path = path + "\\" + b
  46.     return path
  47.  
  48.  
  49. def splitdrive(p):
  50.     """Split a path into a drive specification (a drive letter followed
  51.     by a colon) and path specification.
  52.     It is always true that drivespec + pathspec == p."""
  53.  
  54.     if p[1:2] == ':':
  55.         return p[0:2], p[2:]
  56.     return '', p
  57.  
  58.  
  59. def split(p):
  60.     """Split a path into head (everything up to the last '/') and tail
  61.     (the rest).  After the trailing '/' is stripped, the invariant
  62.     join(head, tail) == p holds.
  63.     The resulting head won't end in '/' unless it is the root."""
  64.  
  65.     d, p = splitdrive(p)
  66.     # set i to index beyond p's last slash
  67.     i = len(p)
  68.     while i and p[i-1] not in '/\\':
  69.         i = i - 1
  70.     head, tail = p[:i], p[i:]  # now tail has no slashes
  71.     # remove trailing slashes from head, unless it's all slashes
  72.     head2 = head
  73.     while head2 and head2[-1] in '/\\':
  74.         head2 = head2[:-1]
  75.     head = head2 or head
  76.     return d + head, tail
  77.  
  78.  
  79. def splitext(p):
  80.     """Split a path into root and extension.
  81.     The extension is everything starting at the first dot in the last
  82.     pathname component; the root is everything before that.
  83.     It is always true that root + ext == p."""
  84.  
  85.     root, ext = '', ''
  86.     for c in p:
  87.         if c in '/\\':
  88.             root, ext = root + ext + c, ''
  89.         elif c == '.' or ext:
  90.             ext = ext + c
  91.         else:
  92.             root = root + c
  93.     return root, ext
  94.  
  95.  
  96. def basename(p):
  97.     """Return the tail (basename) part of a path."""
  98.  
  99.     return split(p)[1]
  100.  
  101.  
  102. def dirname(p):
  103.     """Return the head (dirname) part of a path."""
  104.  
  105.     return split(p)[0]
  106.  
  107.  
  108. def commonprefix(m):
  109.     """Return the longest prefix of all list elements."""
  110.  
  111.     if not m: return ''
  112.     prefix = m[0]
  113.     for item in m:
  114.         for i in range(len(prefix)):
  115.             if prefix[:i+1] != item[:i+1]:
  116.                 prefix = prefix[:i]
  117.                 if i == 0: return ''
  118.                 break
  119.     return prefix
  120.  
  121.  
  122. # Get size, mtime, atime of files.
  123.  
  124. def getsize(filename):
  125.     """Return the size of a file, reported by os.stat()."""
  126.     st = os.stat(filename)
  127.     return st[stat.ST_SIZE]
  128.  
  129. def getmtime(filename):
  130.     """Return the last modification time of a file, reported by os.stat()."""
  131.     st = os.stat(filename)
  132.     return st[stat.ST_MTIME]
  133.  
  134. def getatime(filename):
  135.     """Return the last access time of a file, reported by os.stat()."""
  136.     st = os.stat(filename)
  137.     return st[stat.ST_ATIME]
  138.  
  139.  
  140. def islink(path):
  141.     """Is a path a symbolic link?
  142.     This will always return false on systems where posix.lstat doesn't exist."""
  143.  
  144.     return 0
  145.  
  146.  
  147. def exists(path):
  148.     """Does a path exist?
  149.     This is false for dangling symbolic links."""
  150.  
  151.     try:
  152.         st = os.stat(path)
  153.     except os.error:
  154.         return 0
  155.     return 1
  156.  
  157.  
  158. def isdir(path):
  159.     """Is a path a dos directory?"""
  160.  
  161.     try:
  162.         st = os.stat(path)
  163.     except os.error:
  164.         return 0
  165.     return stat.S_ISDIR(st[stat.ST_MODE])
  166.  
  167.  
  168. def isfile(path):
  169.     """Is a path a regular file?"""
  170.  
  171.     try:
  172.         st = os.stat(path)
  173.     except os.error:
  174.         return 0
  175.     return stat.S_ISREG(st[stat.ST_MODE])
  176.  
  177.  
  178. def ismount(path):
  179.     """Is a path a mount point?"""
  180.     # XXX This degenerates in: 'is this the root?' on DOS
  181.  
  182.     return isabs(splitdrive(path)[1])
  183.  
  184.  
  185. def walk(top, func, arg):
  186.     """Directory tree walk.
  187.     For each directory under top (including top itself, but excluding
  188.     '.' and '..'), func(arg, dirname, filenames) is called, where
  189.     dirname is the name of the directory and filenames is the list
  190.     files files (and subdirectories etc.) in the directory.
  191.     The func may modify the filenames list, to implement a filter,
  192.     or to impose a different order of visiting."""
  193.  
  194.     try:
  195.         names = os.listdir(top)
  196.     except os.error:
  197.         return
  198.     func(arg, top, names)
  199.     exceptions = ('.', '..')
  200.     for name in names:
  201.         if name not in exceptions:
  202.             name = join(top, name)
  203.             if isdir(name):
  204.                 walk(name, func, arg)
  205.  
  206.  
  207. def expanduser(path):
  208.     """Expand paths beginning with '~' or '~user'.
  209.     '~' means $HOME; '~user' means that user's home directory.
  210.     If the path doesn't begin with '~', or if the user or $HOME is unknown,
  211.     the path is returned unchanged (leaving error reporting to whatever
  212.     function is called with the expanded path as argument).
  213.     See also module 'glob' for expansion of *, ? and [...] in pathnames.
  214.     (A function should also be defined to do full *sh-style environment
  215.     variable expansion.)"""
  216.  
  217.     if path[:1] != '~':
  218.         return path
  219.     i, n = 1, len(path)
  220.     while i < n and path[i] not in '/\\':
  221.         i = i+1
  222.     if i == 1:
  223.         if not os.environ.has_key('HOME'):
  224.             return path
  225.         userhome = os.environ['HOME']
  226.     else:
  227.         return path
  228.     return userhome + path[i:]
  229.  
  230.  
  231. def expandvars(path):
  232.     """Expand paths containing shell variable substitutions.
  233.     The following rules apply:
  234.         - no expansion within single quotes
  235.         - no escape character, except for '$$' which is translated into '$'
  236.         - ${varname} is accepted.
  237.         - varnames can be made out of letters, digits and the character '_'"""
  238.     # XXX With COMMAND.COM you can use any characters in a variable name,
  239.     # XXX except '^|<>='.
  240.  
  241.     if '$' not in path:
  242.         return path
  243.     import string
  244.     varchars = string.letters + string.digits + '_-'
  245.     res = ''
  246.     index = 0
  247.     pathlen = len(path)
  248.     while index < pathlen:
  249.         c = path[index]
  250.         if c == '\'':   # no expansion within single quotes
  251.             path = path[index + 1:]
  252.             pathlen = len(path)
  253.             try:
  254.                 index = path.index('\'')
  255.                 res = res + '\'' + path[:index + 1]
  256.             except ValueError:
  257.                 res = res + path
  258.                 index = pathlen -1
  259.         elif c == '$':  # variable or '$$'
  260.             if path[index + 1:index + 2] == '$':
  261.                 res = res + c
  262.                 index = index + 1
  263.             elif path[index + 1:index + 2] == '{':
  264.                 path = path[index+2:]
  265.                 pathlen = len(path)
  266.                 try:
  267.                     index = path.index('}')
  268.                     var = path[:index]
  269.                     if os.environ.has_key(var):
  270.                         res = res + os.environ[var]
  271.                 except ValueError:
  272.                     res = res + path
  273.                     index = pathlen - 1
  274.             else:
  275.                 var = ''
  276.                 index = index + 1
  277.                 c = path[index:index + 1]
  278.                 while c != '' and c in varchars:
  279.                     var = var + c
  280.                     index = index + 1
  281.                     c = path[index:index + 1]
  282.                 if os.environ.has_key(var):
  283.                     res = res + os.environ[var]
  284.                 if c != '':
  285.                     res = res + c
  286.         else:
  287.             res = res + c
  288.         index = index + 1
  289.     return res
  290.  
  291.  
  292. def normpath(path):
  293.     """Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
  294.     Also, components of the path are silently truncated to 8+3 notation."""
  295.  
  296.     path = path.replace("/", "\\")
  297.     prefix, path = splitdrive(path)
  298.     while path[:1] == "\\":
  299.         prefix = prefix + "\\"
  300.         path = path[1:]
  301.     comps = path.split("\\")
  302.     i = 0
  303.     while i < len(comps):
  304.         if comps[i] == '.':
  305.             del comps[i]
  306.         elif comps[i] == '..' and i > 0 and \
  307.                       comps[i-1] not in ('', '..'):
  308.             del comps[i-1:i+1]
  309.             i = i - 1
  310.         elif comps[i] == '' and i > 0 and comps[i-1] != '':
  311.             del comps[i]
  312.         elif '.' in comps[i]:
  313.             comp = comps[i].split('.')
  314.             comps[i] = comp[0][:8] + '.' + comp[1][:3]
  315.             i = i + 1
  316.         elif len(comps[i]) > 8:
  317.             comps[i] = comps[i][:8]
  318.             i = i + 1
  319.         else:
  320.             i = i + 1
  321.     # If the path is now empty, substitute '.'
  322.     if not prefix and not comps:
  323.         comps.append('.')
  324.     return prefix + "\\".join(comps)
  325.  
  326.  
  327.  
  328. def abspath(path):
  329.     """Return an absolute path."""
  330.     if not isabs(path):
  331.         path = join(os.getcwd(), path)
  332.     return normpath(path)
  333.