PyXR

c:\python24\lib \ os2emxpath.py



0001 # Module 'os2emxpath' -- common operations on OS/2 pathnames
0002 """Common pathname manipulations, OS/2 EMX version.
0003 
0004 Instead of importing this module directly, import os and refer to this
0005 module as os.path.
0006 """
0007 
0008 import os
0009 import stat
0010 
0011 __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
0012            "basename","dirname","commonprefix","getsize","getmtime",
0013            "getatime","getctime", "islink","exists","isdir","isfile","ismount",
0014            "walk","expanduser","expandvars","normpath","abspath","splitunc",
0015            "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
0016            "devnull","realpath","supports_unicode_filenames"]
0017 
0018 # strings representing various path-related bits and pieces
0019 curdir = '.'
0020 pardir = '..'
0021 extsep = '.'
0022 sep = '/'
0023 altsep = '\\'
0024 pathsep = ';'
0025 defpath = '.;C:\\bin'
0026 devnull = 'nul'
0027 
0028 # Normalize the case of a pathname and map slashes to backslashes.
0029 # Other normalizations (such as optimizing '../' away) are not done
0030 # (this is done by normpath).
0031 
0032 def normcase(s):
0033     """Normalize case of pathname.
0034 
0035     Makes all characters lowercase and all altseps into seps."""
0036     return s.replace('\\', '/').lower()
0037 
0038 
0039 # Return whether a path is absolute.
0040 # Trivial in Posix, harder on the Mac or MS-DOS.
0041 # For DOS it is absolute if it starts with a slash or backslash (current
0042 # volume), or if a pathname after the volume letter and colon / UNC resource
0043 # starts with a slash or backslash.
0044 
0045 def isabs(s):
0046     """Test whether a path is absolute"""
0047     s = splitdrive(s)[1]
0048     return s != '' and s[:1] in '/\\'
0049 
0050 
0051 # Join two (or more) paths.
0052 
0053 def join(a, *p):
0054     """Join two or more pathname components, inserting sep as needed"""
0055     path = a
0056     for b in p:
0057         if isabs(b):
0058             path = b
0059         elif path == '' or path[-1:] in '/\\:':
0060             path = path + b
0061         else:
0062             path = path + '/' + b
0063     return path
0064 
0065 
0066 # Split a path in a drive specification (a drive letter followed by a
0067 # colon) and the path specification.
0068 # It is always true that drivespec + pathspec == p
0069 def splitdrive(p):
0070     """Split a pathname into drive and path specifiers. Returns a 2-tuple
0071 "(drive,path)";  either part may be empty"""
0072     if p[1:2] == ':':
0073         return p[0:2], p[2:]
0074     return '', p
0075 
0076 
0077 # Parse UNC paths
0078 def splitunc(p):
0079     """Split a pathname into UNC mount point and relative path specifiers.
0080 
0081     Return a 2-tuple (unc, rest); either part may be empty.
0082     If unc is not empty, it has the form '//host/mount' (or similar
0083     using backslashes).  unc+rest is always the input path.
0084     Paths containing drive letters never have an UNC part.
0085     """
0086     if p[1:2] == ':':
0087         return '', p # Drive letter present
0088     firstTwo = p[0:2]
0089     if firstTwo == '/' * 2 or firstTwo == '\\' * 2:
0090         # is a UNC path:
0091         # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
0092         # \\machine\mountpoint\directories...
0093         #           directory ^^^^^^^^^^^^^^^
0094         normp = normcase(p)
0095         index = normp.find('/', 2)
0096         if index == -1:
0097             ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
0098             return ("", p)
0099         index = normp.find('/', index + 1)
0100         if index == -1:
0101             index = len(p)
0102         return p[:index], p[index:]
0103     return '', p
0104 
0105 
0106 # Split a path in head (everything up to the last '/') and tail (the
0107 # rest).  After the trailing '/' is stripped, the invariant
0108 # join(head, tail) == p holds.
0109 # The resulting head won't end in '/' unless it is the root.
0110 
0111 def split(p):
0112     """Split a pathname.
0113 
0114     Return tuple (head, tail) where tail is everything after the final slash.
0115     Either part may be empty."""
0116 
0117     d, p = splitdrive(p)
0118     # set i to index beyond p's last slash
0119     i = len(p)
0120     while i and p[i-1] not in '/\\':
0121         i = i - 1
0122     head, tail = p[:i], p[i:]  # now tail has no slashes
0123     # remove trailing slashes from head, unless it's all slashes
0124     head2 = head
0125     while head2 and head2[-1] in '/\\':
0126         head2 = head2[:-1]
0127     head = head2 or head
0128     return d + head, tail
0129 
0130 
0131 # Split a path in root and extension.
0132 # The extension is everything starting at the last dot in the last
0133 # pathname component; the root is everything before that.
0134 # It is always true that root + ext == p.
0135 
0136 def splitext(p):
0137     """Split the extension from a pathname.
0138 
0139     Extension is everything from the last dot to the end.
0140     Return (root, ext), either part may be empty."""
0141     root, ext = '', ''
0142     for c in p:
0143         if c in ['/','\\']:
0144             root, ext = root + ext + c, ''
0145         elif c == '.':
0146             if ext:
0147                 root, ext = root + ext, c
0148             else:
0149                 ext = c
0150         elif ext:
0151             ext = ext + c
0152         else:
0153             root = root + c
0154     return root, ext
0155 
0156 
0157 # Return the tail (basename) part of a path.
0158 
0159 def basename(p):
0160     """Returns the final component of a pathname"""
0161     return split(p)[1]
0162 
0163 
0164 # Return the head (dirname) part of a path.
0165 
0166 def dirname(p):
0167     """Returns the directory component of a pathname"""
0168     return split(p)[0]
0169 
0170 
0171 # Return the longest prefix of all list elements.
0172 
0173 def commonprefix(m):
0174     "Given a list of pathnames, returns the longest common leading component"
0175     if not m: return ''
0176     prefix = m[0]
0177     for item in m:
0178         for i in range(len(prefix)):
0179             if prefix[:i+1] != item[:i+1]:
0180                 prefix = prefix[:i]
0181                 if i == 0: return ''
0182                 break
0183     return prefix
0184 
0185 
0186 # Get size, mtime, atime of files.
0187 
0188 def getsize(filename):
0189     """Return the size of a file, reported by os.stat()"""
0190     return os.stat(filename).st_size
0191 
0192 def getmtime(filename):
0193     """Return the last modification time of a file, reported by os.stat()"""
0194     return os.stat(filename).st_mtime
0195 
0196 def getatime(filename):
0197     """Return the last access time of a file, reported by os.stat()"""
0198     return os.stat(filename).st_atime
0199 
0200 def getctime(filename):
0201     """Return the creation time of a file, reported by os.stat()."""
0202     return os.stat(filename).st_ctime
0203 
0204 # Is a path a symbolic link?
0205 # This will always return false on systems where posix.lstat doesn't exist.
0206 
0207 def islink(path):
0208     """Test for symbolic link.  On OS/2 always returns false"""
0209     return False
0210 
0211 
0212 # Does a path exist?
0213 # This is false for dangling symbolic links.
0214 
0215 def exists(path):
0216     """Test whether a path exists"""
0217     try:
0218         st = os.stat(path)
0219     except os.error:
0220         return False
0221     return True
0222 
0223 lexists = exists
0224 
0225 
0226 # Is a path a directory?
0227 
0228 def isdir(path):
0229     """Test whether a path is a directory"""
0230     try:
0231         st = os.stat(path)
0232     except os.error:
0233         return False
0234     return stat.S_ISDIR(st.st_mode)
0235 
0236 
0237 # Is a path a regular file?
0238 # This follows symbolic links, so both islink() and isdir() can be true
0239 # for the same path.
0240 
0241 def isfile(path):
0242     """Test whether a path is a regular file"""
0243     try:
0244         st = os.stat(path)
0245     except os.error:
0246         return False
0247     return stat.S_ISREG(st.st_mode)
0248 
0249 
0250 # Is a path a mount point?  Either a root (with or without drive letter)
0251 # or an UNC path with at most a / or \ after the mount point.
0252 
0253 def ismount(path):
0254     """Test whether a path is a mount point (defined as root of drive)"""
0255     unc, rest = splitunc(path)
0256     if unc:
0257         return rest in ("", "/", "\\")
0258     p = splitdrive(path)[1]
0259     return len(p) == 1 and p[0] in '/\\'
0260 
0261 
0262 # Directory tree walk.
0263 # For each directory under top (including top itself, but excluding
0264 # '.' and '..'), func(arg, dirname, filenames) is called, where
0265 # dirname is the name of the directory and filenames is the list
0266 # of files (and subdirectories etc.) in the directory.
0267 # The func may modify the filenames list, to implement a filter,
0268 # or to impose a different order of visiting.
0269 
0270 def walk(top, func, arg):
0271     """Directory tree walk whth callback function.
0272 
0273     walk(top, func, arg) calls func(arg, d, files) for each directory d
0274     in the tree rooted at top (including top itself); files is a list
0275     of all the files and subdirs in directory d."""
0276     try:
0277         names = os.listdir(top)
0278     except os.error:
0279         return
0280     func(arg, top, names)
0281     exceptions = ('.', '..')
0282     for name in names:
0283         if name not in exceptions:
0284             name = join(top, name)
0285             if isdir(name):
0286                 walk(name, func, arg)
0287 
0288 
0289 # Expand paths beginning with '~' or '~user'.
0290 # '~' means $HOME; '~user' means that user's home directory.
0291 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
0292 # the path is returned unchanged (leaving error reporting to whatever
0293 # function is called with the expanded path as argument).
0294 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
0295 # (A function should also be defined to do full *sh-style environment
0296 # variable expansion.)
0297 
0298 def expanduser(path):
0299     """Expand ~ and ~user constructs.
0300 
0301     If user or $HOME is unknown, do nothing."""
0302     if path[:1] != '~':
0303         return path
0304     i, n = 1, len(path)
0305     while i < n and path[i] not in '/\\':
0306         i = i + 1
0307     if i == 1:
0308         if 'HOME' in os.environ:
0309             userhome = os.environ['HOME']
0310         elif not 'HOMEPATH' in os.environ:
0311             return path
0312         else:
0313             try:
0314                 drive = os.environ['HOMEDRIVE']
0315             except KeyError:
0316                 drive = ''
0317             userhome = join(drive, os.environ['HOMEPATH'])
0318     else:
0319         return path
0320     return userhome + path[i:]
0321 
0322 
0323 # Expand paths containing shell variable substitutions.
0324 # The following rules apply:
0325 #       - no expansion within single quotes
0326 #       - no escape character, except for '$$' which is translated into '$'
0327 #       - ${varname} is accepted.
0328 #       - varnames can be made out of letters, digits and the character '_'
0329 # XXX With COMMAND.COM you can use any characters in a variable name,
0330 # XXX except '^|<>='.
0331 
0332 def expandvars(path):
0333     """Expand shell variables of form $var and ${var}.
0334 
0335     Unknown variables are left unchanged."""
0336     if '$' not in path:
0337         return path
0338     import string
0339     varchars = string.letters + string.digits + '_-'
0340     res = ''
0341     index = 0
0342     pathlen = len(path)
0343     while index < pathlen:
0344         c = path[index]
0345         if c == '\'':   # no expansion within single quotes
0346             path = path[index + 1:]
0347             pathlen = len(path)
0348             try:
0349                 index = path.index('\'')
0350                 res = res + '\'' + path[:index + 1]
0351             except ValueError:
0352                 res = res + path
0353                 index = pathlen - 1
0354         elif c == '$':  # variable or '$$'
0355             if path[index + 1:index + 2] == '$':
0356                 res = res + c
0357                 index = index + 1
0358             elif path[index + 1:index + 2] == '{':
0359                 path = path[index+2:]
0360                 pathlen = len(path)
0361                 try:
0362                     index = path.index('}')
0363                     var = path[:index]
0364                     if var in os.environ:
0365                         res = res + os.environ[var]
0366                 except ValueError:
0367                     res = res + path
0368                     index = pathlen - 1
0369             else:
0370                 var = ''
0371                 index = index + 1
0372                 c = path[index:index + 1]
0373                 while c != '' and c in varchars:
0374                     var = var + c
0375                     index = index + 1
0376                     c = path[index:index + 1]
0377                 if var in os.environ:
0378                     res = res + os.environ[var]
0379                 if c != '':
0380                     res = res + c
0381         else:
0382             res = res + c
0383         index = index + 1
0384     return res
0385 
0386 
0387 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
0388 
0389 def normpath(path):
0390     """Normalize path, eliminating double slashes, etc."""
0391     path = path.replace('\\', '/')
0392     prefix, path = splitdrive(path)
0393     while path[:1] == '/':
0394         prefix = prefix + '/'
0395         path = path[1:]
0396     comps = path.split('/')
0397     i = 0
0398     while i < len(comps):
0399         if comps[i] == '.':
0400             del comps[i]
0401         elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
0402             del comps[i-1:i+1]
0403             i = i - 1
0404         elif comps[i] == '' and i > 0 and comps[i-1] != '':
0405             del comps[i]
0406         else:
0407             i = i + 1
0408     # If the path is now empty, substitute '.'
0409     if not prefix and not comps:
0410         comps.append('.')
0411     return prefix + '/'.join(comps)
0412 
0413 
0414 # Return an absolute path.
0415 def abspath(path):
0416     """Return the absolute version of a path"""
0417     if not isabs(path):
0418         path = join(os.getcwd(), path)
0419     return normpath(path)
0420 
0421 # realpath is a no-op on systems without islink support
0422 realpath = abspath
0423 
0424 supports_unicode_filenames = False
0425 

Generated by PyXR 0.9.4
SourceForge.net Logo