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 / os.py.z / os.py
Encoding:
Python Source  |  1999-04-16  |  7.3 KB  |  261 lines

  1. # os.py -- either mac, dos or posix depending on what system we're on.
  2.  
  3. # This exports:
  4. # - all functions from either posix or mac, e.g., os.unlink, os.stat, etc.
  5. # - os.path is either module posixpath or macpath
  6. # - os.name is either 'posix' or 'mac'
  7. # - os.curdir is a string representing the current directory ('.' or ':')
  8. # - os.pardir is a string representing the parent directory ('..' or '::')
  9. # - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
  10. # - os.altsep is the alternatte pathname separator (None or '/')
  11. # - os.pathsep is the component separator used in $PATH etc
  12. # - os.defpath is the default search path for executables
  13.  
  14. # Programs that import and use 'os' stand a better chance of being
  15. # portable between different platforms.  Of course, they must then
  16. # only use functions that are defined by all platforms (e.g., unlink
  17. # and opendir), and leave all pathname manipulation to os.path
  18. # (e.g., split and join).
  19.  
  20. import sys
  21.  
  22. _names = sys.builtin_module_names
  23.  
  24. altsep = None
  25.  
  26. if 'posix' in _names:
  27.     name = 'posix'
  28.     linesep = '\n'
  29.     curdir = '.'; pardir = '..'; sep = '/'; pathsep = ':'
  30.     defpath = ':/bin:/usr/bin'
  31.     from posix import *
  32.     try:
  33.         from posix import _exit
  34.     except ImportError:
  35.         pass
  36.     import posixpath
  37.     path = posixpath
  38.     del posixpath
  39. elif 'nt' in _names:
  40.     name = 'nt'
  41.     linesep = '\r\n'
  42.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  43.     defpath = '.;C:\\bin'
  44.     from nt import *
  45.     for i in ['_exit',
  46.               '_P_WAIT', '_P_NOWAIT', '_P_OVERLAY',
  47.               '_P_NOWAITO', '_P_DETACH']:
  48.         try:
  49.             exec "from nt import " + i
  50.         except ImportError:
  51.             pass
  52.     import ntpath
  53.     path = ntpath
  54.     del ntpath
  55. elif 'dos' in _names:
  56.     name = 'dos'
  57.     linesep = '\r\n'
  58.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  59.     defpath = '.;C:\\bin'
  60.     from dos import *
  61.     try:
  62.         from dos import _exit
  63.     except ImportError:
  64.         pass
  65.     import dospath
  66.     path = dospath
  67.     del dospath
  68. elif 'os2' in _names:
  69.     name = 'os2'
  70.     linesep = '\r\n'
  71.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  72.     defpath = '.;C:\\bin'
  73.     from os2 import *
  74.     try:
  75.         from os2 import _exit
  76.     except ImportError:
  77.         pass
  78.     import ntpath
  79.     path = ntpath
  80.     del ntpath
  81. elif 'mac' in _names:
  82.     name = 'mac'
  83.     linesep = '\r'
  84.     curdir = ':'; pardir = '::'; sep = ':'; pathsep = '\n'
  85.     defpath = ':'
  86.     from mac import *
  87.     try:
  88.         from mac import _exit
  89.     except ImportError:
  90.         pass
  91.     import macpath
  92.     path = macpath
  93.     del macpath
  94. else:
  95.     raise ImportError, 'no os specific module found'
  96.  
  97. del _names
  98.  
  99. sys.modules['os.path'] = path
  100.  
  101. # Super directory utilities.
  102. # (Inspired by Eric Raymond; the doc strings are mostly his)
  103.  
  104. def makedirs(name, mode=0777):
  105.     """makedirs(path [, mode=0777]) -> None
  106.  
  107.     Super-mkdir; create a leaf directory and all intermediate ones.
  108.     Works like mkdir, except that any intermediate path segment (not
  109.     just the rightmost) will be created if it does not exist.  This is
  110.     recursive.
  111.  
  112.     """
  113.     head, tail = path.split(name)
  114.     if head and tail and not path.exists(head):
  115.         makedirs(head, mode)
  116.     mkdir(name, mode)
  117.  
  118. def removedirs(name):
  119.     """removedirs(path) -> None
  120.  
  121.     Super-rmdir; remove a leaf directory and empty all intermediate
  122.     ones.  Works like rmdir except that, if the leaf directory is
  123.     successfully removed, directories corresponding to rightmost path
  124.     segments will be pruned way until either the whole path is
  125.     consumed or an error occurs.  Errors during this latter phase are
  126.     ignored -- they generally mean that a directory was not empty.
  127.  
  128.     """
  129.     rmdir(name)
  130.     head, tail = path.split(name)
  131.     while head and tail:
  132.         try:
  133.             rmdir(head)
  134.         except error:
  135.             break
  136.         head, tail = path.split(head)
  137.  
  138. def renames(old, new):
  139.     """renames(old, new) -> None
  140.  
  141.     Super-rename; create directories as necessary and delete any left
  142.     empty.  Works like rename, except creation of any intermediate
  143.     directories needed to make the new pathname good is attempted
  144.     first.  After the rename, directories corresponding to rightmost
  145.     path segments of the old name will be pruned way until either the
  146.     whole path is consumed or a nonempty directory is found.
  147.  
  148.     Note: this function can fail with the new directory structure made
  149.     if you lack permissions needed to unlink the leaf directory or
  150.     file.
  151.  
  152.     """
  153.     head, tail = path.split(new)
  154.     if head and tail and not path.exists(head):
  155.         makedirs(head)
  156.     rename(old, new)
  157.     head, tail = path.split(old)
  158.     if head and tail:
  159.         try:
  160.             removedirs(head)
  161.         except error:
  162.             pass
  163.  
  164. # Make sure os.environ exists, at least
  165. try:
  166.     environ
  167. except NameError:
  168.     environ = {}
  169.  
  170. def execl(file, *args):
  171.     execv(file, args)
  172.  
  173. def execle(file, *args):
  174.     env = args[-1]
  175.     execve(file, args[:-1], env)
  176.  
  177. def execlp(file, *args):
  178.     execvp(file, args)
  179.  
  180. def execlpe(file, *args):
  181.     env = args[-1]
  182.     execvpe(file, args[:-1], env)
  183.  
  184. def execvp(file, args):
  185.     _execvpe(file, args)
  186.  
  187. def execvpe(file, args, env):
  188.     _execvpe(file, args, env)
  189.  
  190. _notfound = None
  191. def _execvpe(file, args, env = None):
  192.     if env:
  193.         func = execve
  194.         argrest = (args, env)
  195.     else:
  196.         func = execv
  197.         argrest = (args,)
  198.         env = environ
  199.     global _notfound
  200.     head, tail = path.split(file)
  201.     if head:
  202.         apply(func, (file,) + argrest)
  203.         return
  204.     if env.has_key('PATH'):
  205.         envpath = env['PATH']
  206.     else:
  207.         envpath = defpath
  208.     import string
  209.     PATH = string.splitfields(envpath, pathsep)
  210.     if not _notfound:
  211.         import tempfile
  212.         # Exec a file that is guaranteed not to exist
  213.         try: execv(tempfile.mktemp(), ())
  214.         except error, _notfound: pass
  215.     exc, arg = error, _notfound
  216.     for dir in PATH:
  217.         fullname = path.join(dir, file)
  218.         try:
  219.             apply(func, (fullname,) + argrest)
  220.         except error, (errno, msg):
  221.             if errno != arg[0]:
  222.                 exc, arg = error, (errno, msg)
  223.     raise exc, arg
  224.  
  225. # Change environ to automatically call putenv() if it exists
  226. try:
  227.     # This will fail if there's no putenv
  228.     putenv
  229. except NameError:
  230.     pass
  231. else:
  232.     import UserDict
  233.  
  234.     if name in ('os2', 'nt', 'dos'):  # Where Env Var Names Must Be UPPERCASE
  235.         # But we store them as upper case
  236.         import string
  237.         class _Environ(UserDict.UserDict):
  238.             def __init__(self, environ):
  239.                 UserDict.UserDict.__init__(self)
  240.                 data = self.data
  241.                 upper = string.upper
  242.                 for k, v in environ.items():
  243.                     data[upper(k)] = v
  244.             def __setitem__(self, key, item):
  245.                 putenv(key, item)
  246.                 key = string.upper(key)
  247.                 self.data[key] = item
  248.             def __getitem__(self, key):
  249.                 return self.data[string.upper(key)]
  250.  
  251.     else:  # Where Env Var Names Can Be Mixed Case
  252.         class _Environ(UserDict.UserDict):
  253.             def __init__(self, environ):
  254.                 UserDict.UserDict.__init__(self)
  255.                 self.data = environ
  256.             def __setitem__(self, key, item):
  257.                 putenv(key, item)
  258.                 self.data[key] = item
  259.  
  260.     environ = _Environ(environ)
  261.