home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pytho152.zip / emx / lib / python1.5 / os.py < prev    next >
Text File  |  2000-08-10  |  7KB  |  259 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.         try:
  47.             exec "from nt import " + i
  48.         except ImportError:
  49.             pass
  50.     import ntpath
  51.     path = ntpath
  52.     del ntpath
  53. elif 'dos' in _names:
  54.     name = 'dos'
  55.     linesep = '\r\n'
  56.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  57.     defpath = '.;C:\\bin'
  58.     from dos import *
  59.     try:
  60.         from dos import _exit
  61.     except ImportError:
  62.         pass
  63.     import dospath
  64.     path = dospath
  65.     del dospath
  66. elif 'os2' in _names:
  67.     name = 'os2'
  68.     linesep = '\r\n'
  69.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  70.     defpath = '.;C:\\bin'
  71.     from os2 import *
  72.     try:
  73.         from os2 import _exit
  74.     except ImportError:
  75.         pass
  76.     import ntpath
  77.     path = ntpath
  78.     del ntpath
  79. elif 'mac' in _names:
  80.     name = 'mac'
  81.     linesep = '\r'
  82.     curdir = ':'; pardir = '::'; sep = ':'; pathsep = '\n'
  83.     defpath = ':'
  84.     from mac import *
  85.     try:
  86.         from mac import _exit
  87.     except ImportError:
  88.         pass
  89.     import macpath
  90.     path = macpath
  91.     del macpath
  92. else:
  93.     raise ImportError, 'no os specific module found'
  94.  
  95. del _names
  96.  
  97. sys.modules['os.path'] = path
  98.  
  99. # Super directory utilities.
  100. # (Inspired by Eric Raymond; the doc strings are mostly his)
  101.  
  102. def makedirs(name, mode=0777):
  103.     """makedirs(path [, mode=0777]) -> None
  104.  
  105.     Super-mkdir; create a leaf directory and all intermediate ones.
  106.     Works like mkdir, except that any intermediate path segment (not
  107.     just the rightmost) will be created if it does not exist.  This is
  108.     recursive.
  109.  
  110.     """
  111.     head, tail = path.split(name)
  112.     if head and tail and not path.exists(head):
  113.         makedirs(head, mode)
  114.     mkdir(name, mode)
  115.  
  116. def removedirs(name):
  117.     """removedirs(path) -> None
  118.  
  119.     Super-rmdir; remove a leaf directory and empty all intermediate
  120.     ones.  Works like rmdir except that, if the leaf directory is
  121.     successfully removed, directories corresponding to rightmost path
  122.     segments will be pruned way until either the whole path is
  123.     consumed or an error occurs.  Errors during this latter phase are
  124.     ignored -- they generally mean that a directory was not empty.
  125.  
  126.     """
  127.     rmdir(name)
  128.     head, tail = path.split(name)
  129.     while head and tail:
  130.         try:
  131.             rmdir(head)
  132.         except error:
  133.             break
  134.         head, tail = path.split(head)
  135.  
  136. def renames(old, new):
  137.     """renames(old, new) -> None
  138.  
  139.     Super-rename; create directories as necessary and delete any left
  140.     empty.  Works like rename, except creation of any intermediate
  141.     directories needed to make the new pathname good is attempted
  142.     first.  After the rename, directories corresponding to rightmost
  143.     path segments of the old name will be pruned way until either the
  144.     whole path is consumed or a nonempty directory is found.
  145.  
  146.     Note: this function can fail with the new directory structure made
  147.     if you lack permissions needed to unlink the leaf directory or
  148.     file.
  149.  
  150.     """
  151.     head, tail = path.split(new)
  152.     if head and tail and not path.exists(head):
  153.         makedirs(head)
  154.     rename(old, new)
  155.     head, tail = path.split(old)
  156.     if head and tail:
  157.         try:
  158.             removedirs(head)
  159.         except error:
  160.             pass
  161.  
  162. # Make sure os.environ exists, at least
  163. try:
  164.     environ
  165. except NameError:
  166.     environ = {}
  167.  
  168. def execl(file, *args):
  169.     execv(file, args)
  170.  
  171. def execle(file, *args):
  172.     env = args[-1]
  173.     execve(file, args[:-1], env)
  174.  
  175. def execlp(file, *args):
  176.     execvp(file, args)
  177.  
  178. def execlpe(file, *args):
  179.     env = args[-1]
  180.     execvpe(file, args[:-1], env)
  181.  
  182. def execvp(file, args):
  183.     _execvpe(file, args)
  184.  
  185. def execvpe(file, args, env):
  186.     _execvpe(file, args, env)
  187.  
  188. _notfound = None
  189. def _execvpe(file, args, env = None):
  190.     if env:
  191.         func = execve
  192.         argrest = (args, env)
  193.     else:
  194.         func = execv
  195.         argrest = (args,)
  196.         env = environ
  197.     global _notfound
  198.     head, tail = path.split(file)
  199.     if head:
  200.         apply(func, (file,) + argrest)
  201.         return
  202.     if env.has_key('PATH'):
  203.         envpath = env['PATH']
  204.     else:
  205.         envpath = defpath
  206.     import string
  207.     PATH = string.splitfields(envpath, pathsep)
  208.     if not _notfound:
  209.         import tempfile
  210.         # Exec a file that is guaranteed not to exist
  211.         try: execv(tempfile.mktemp(), ())
  212.         except error, _notfound: pass
  213.     exc, arg = error, _notfound
  214.     for dir in PATH:
  215.         fullname = path.join(dir, file)
  216.         try:
  217.             apply(func, (fullname,) + argrest)
  218.         except error, (errno, msg):
  219.             if errno != arg[0]:
  220.                 exc, arg = error, (errno, msg)
  221.     raise exc, arg
  222.  
  223. # Change environ to automatically call putenv() if it exists
  224. try:
  225.     # This will fail if there's no putenv
  226.     putenv
  227. except NameError:
  228.     pass
  229. else:
  230.     import UserDict
  231.  
  232.     if name in ('os2', 'nt', 'dos'):  # Where Env Var Names Must Be UPPERCASE
  233.         # But we store them as upper case
  234.         import string
  235.         class _Environ(UserDict.UserDict):
  236.             def __init__(self, environ):
  237.                 UserDict.UserDict.__init__(self)
  238.                 data = self.data
  239.                 upper = string.upper
  240.                 for k, v in environ.items():
  241.                     data[upper(k)] = v
  242.             def __setitem__(self, key, item):
  243.                 putenv(key, item)
  244.                 key = string.upper(key)
  245.                 self.data[key] = item
  246.             def __getitem__(self, key):
  247.                 return self.data[string.upper(key)]
  248.  
  249.     else:  # Where Env Var Names Can Be Mixed Case
  250.         class _Environ(UserDict.UserDict):
  251.             def __init__(self, environ):
  252.                 UserDict.UserDict.__init__(self)
  253.                 self.data = environ
  254.             def __setitem__(self, key, item):
  255.                 putenv(key, item)
  256.                 self.data[key] = item
  257.  
  258.     environ = _Environ(environ)
  259.