home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Lib / Python2.0 / os.py < prev    next >
Encoding:
Python Source  |  2000-10-28  |  15.2 KB  |  489 lines

  1. """OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
  2.  
  3. This exports:
  4.   - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc.
  5.   - os.path is one of the modules posixpath, ntpath, macpath, or dospath
  6.   - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', or 'ce'
  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 alternate pathname separator (None or '/')
  11.   - os.pathsep is the component separator used in $PATH etc
  12.   - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  13.   - os.defpath is the default search path for executables
  14.  
  15. Programs that import and use 'os' stand a better chance of being
  16. portable between different platforms.  Of course, they must then
  17. only use functions that are defined by all platforms (e.g., unlink
  18. and opendir), and leave all pathname manipulation to os.path
  19. (e.g., split and join).
  20. """
  21.  
  22. import sys
  23.  
  24. _names = sys.builtin_module_names
  25.  
  26. altsep = None
  27.  
  28. if 'posix' in _names:
  29.     name = 'posix'
  30.     linesep = '\n'
  31.     curdir = '.'; pardir = '..'; sep = '/'; pathsep = ':'
  32.     defpath = ':/bin:/usr/bin'
  33.     from posix import *
  34.     try:
  35.         from posix import _exit
  36.     except ImportError:
  37.         pass
  38.     import posixpath
  39.     path = posixpath
  40.     del posixpath
  41. elif 'amiga' in _names:
  42.     name = 'amiga'
  43.     linesep = '\n'
  44.     curdir = ''; pardir = '/'; sep = '/'; pathsep = ';'
  45.     defpath = 'C:'
  46.     from amiga import *
  47.     try:
  48.         from amiga import _exit
  49.     except ImportError:
  50.         pass
  51.     import amigapath
  52.     path = amigapath
  53.     del amigapath
  54. elif 'nt' in _names:
  55.     name = 'nt'
  56.     linesep = '\r\n'
  57.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  58.     defpath = '.;C:\\bin'
  59.     from nt import *
  60.     for i in ['_exit']:
  61.         try:
  62.             exec "from nt import " + i
  63.         except ImportError:
  64.             pass
  65.     import ntpath
  66.     path = ntpath
  67.     del ntpath
  68. elif 'dos' in _names:
  69.     name = 'dos'
  70.     linesep = '\r\n'
  71.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  72.     defpath = '.;C:\\bin'
  73.     from dos import *
  74.     try:
  75.         from dos import _exit
  76.     except ImportError:
  77.         pass
  78.     import dospath
  79.     path = dospath
  80.     del dospath
  81. elif 'os2' in _names:
  82.     name = 'os2'
  83.     linesep = '\r\n'
  84.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  85.     defpath = '.;C:\\bin'
  86.     from os2 import *
  87.     try:
  88.         from os2 import _exit
  89.     except ImportError:
  90.         pass
  91.     import ntpath
  92.     path = ntpath
  93.     del ntpath
  94. elif 'mac' in _names:
  95.     name = 'mac'
  96.     linesep = '\r'
  97.     curdir = ':'; pardir = '::'; sep = ':'; pathsep = '\n'
  98.     defpath = ':'
  99.     from mac import *
  100.     try:
  101.         from mac import _exit
  102.     except ImportError:
  103.         pass
  104.     import macpath
  105.     path = macpath
  106.     del macpath
  107. elif 'ce' in _names:
  108.     name = 'ce'
  109.     linesep = '\r\n'
  110.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  111.     defpath = '\\Windows'
  112.     from ce import *
  113.     for i in ['_exit']:
  114.         try:
  115.             exec "from ce import " + i
  116.         except ImportError:
  117.             pass
  118.     # We can use the standard Windows path.
  119.     import ntpath
  120.     path = ntpath
  121.     del ntpath
  122. else:
  123.     raise ImportError, 'no os specific module found'
  124.  
  125. del _names
  126.  
  127. sys.modules['os.path'] = path
  128.  
  129. # Super directory utilities.
  130. # (Inspired by Eric Raymond; the doc strings are mostly his)
  131.  
  132. def makedirs(name, mode=0777):
  133.     """makedirs(path [, mode=0777]) -> None
  134.  
  135.     Super-mkdir; create a leaf directory and all intermediate ones.
  136.     Works like mkdir, except that any intermediate path segment (not
  137.     just the rightmost) will be created if it does not exist.  This is
  138.     recursive.
  139.  
  140.     """
  141.     head, tail = path.split(name)
  142.     if not tail:
  143.         head, tail = path.split(head)
  144.     if head and tail and not path.exists(head):
  145.         makedirs(head, mode)
  146.     mkdir(name, mode)
  147.  
  148. def removedirs(name):
  149.     """removedirs(path) -> None
  150.  
  151.     Super-rmdir; remove a leaf directory and empty all intermediate
  152.     ones.  Works like rmdir except that, if the leaf directory is
  153.     successfully removed, directories corresponding to rightmost path
  154.     segments will be pruned way until either the whole path is
  155.     consumed or an error occurs.  Errors during this latter phase are
  156.     ignored -- they generally mean that a directory was not empty.
  157.  
  158.     """
  159.     rmdir(name)
  160.     head, tail = path.split(name)
  161.     if not tail:
  162.         head, tail = path.split(head)
  163.     while head and tail:
  164.         try:
  165.             rmdir(head)
  166.         except error:
  167.             break
  168.         head, tail = path.split(head)
  169.  
  170. def renames(old, new):
  171.     """renames(old, new) -> None
  172.  
  173.     Super-rename; create directories as necessary and delete any left
  174.     empty.  Works like rename, except creation of any intermediate
  175.     directories needed to make the new pathname good is attempted
  176.     first.  After the rename, directories corresponding to rightmost
  177.     path segments of the old name will be pruned way until either the
  178.     whole path is consumed or a nonempty directory is found.
  179.  
  180.     Note: this function can fail with the new directory structure made
  181.     if you lack permissions needed to unlink the leaf directory or
  182.     file.
  183.  
  184.     """
  185.     head, tail = path.split(new)
  186.     if head and tail and not path.exists(head):
  187.         makedirs(head)
  188.     rename(old, new)
  189.     head, tail = path.split(old)
  190.     if head and tail:
  191.         try:
  192.             removedirs(head)
  193.         except error:
  194.             pass
  195.  
  196. # Make sure os.environ exists, at least
  197. try:
  198.     environ
  199. except NameError:
  200.     environ = {}
  201.  
  202. def execl(file, *args):
  203.     """execl(file, *args)
  204.  
  205.     Execute the executable file with argument list args, replacing the
  206.     current process. """
  207.     execv(file, args)
  208.  
  209. def execle(file, *args):
  210.     """execle(file, *args, env)
  211.  
  212.     Execute the executable file with argument list args and
  213.     environment env, replacing the current process. """
  214.     env = args[-1]
  215.     execve(file, args[:-1], env)
  216.  
  217. def execlp(file, *args):
  218.     """execlp(file, *args)
  219.  
  220.     Execute the executable file (which is searched for along $PATH)
  221.     with argument list args, replacing the current process. """
  222.     execvp(file, args)
  223.  
  224. def execlpe(file, *args):
  225.     """execlpe(file, *args, env)
  226.  
  227.     Execute the executable file (which is searched for along $PATH)
  228.     with argument list args and environment env, replacing the current
  229.     process. """    
  230.     env = args[-1]
  231.     execvpe(file, args[:-1], env)
  232.  
  233. def execvp(file, args):
  234.     """execp(file, args)
  235.  
  236.     Execute the executable file (which is searched for along $PATH)
  237.     with argument list args, replacing the current process.
  238.     args may be a list or tuple of strings. """
  239.     _execvpe(file, args)
  240.  
  241. def execvpe(file, args, env):
  242.     """execv(file, args, env)
  243.  
  244.     Execute the executable file (which is searched for along $PATH)
  245.     with argument list args and environment env , replacing the
  246.     current process.
  247.     args may be a list or tuple of strings. """    
  248.     _execvpe(file, args, env)
  249.  
  250. _notfound = None
  251. def _execvpe(file, args, env=None):
  252.     if env is not None:
  253.         func = execve
  254.         argrest = (args, env)
  255.     else:
  256.         func = execv
  257.         argrest = (args,)
  258.         env = environ
  259.     global _notfound
  260.     head, tail = path.split(file)
  261.     if head:
  262.         apply(func, (file,) + argrest)
  263.         return
  264.     if env.has_key('PATH'):
  265.         envpath = env['PATH']
  266.     else:
  267.         envpath = defpath
  268.     PATH = envpath.split(pathsep)
  269.     if not _notfound:
  270.         import tempfile
  271.         # Exec a file that is guaranteed not to exist
  272.         try: execv(tempfile.mktemp(), ('blah',))
  273.         except error, _notfound: pass
  274.     exc, arg = error, _notfound
  275.     for dir in PATH:
  276.         fullname = path.join(dir, file)
  277.         try:
  278.             apply(func, (fullname,) + argrest)
  279.         except error, (errno, msg):
  280.             if errno != arg[0]:
  281.                 exc, arg = error, (errno, msg)
  282.     raise exc, arg
  283.  
  284. # Change environ to automatically call putenv() if it exists
  285. try:
  286.     # This will fail if there's no putenv
  287.     putenv
  288. except NameError:
  289.     pass
  290. else:
  291.     import UserDict
  292.  
  293.     if name in ('os2', 'nt', 'dos'):  # Where Env Var Names Must Be UPPERCASE
  294.         # But we store them as upper case
  295.         class _Environ(UserDict.UserDict):
  296.             def __init__(self, environ):
  297.                 UserDict.UserDict.__init__(self)
  298.                 data = self.data
  299.                 for k, v in environ.items():
  300.                     data[k.upper()] = v
  301.             def __setitem__(self, key, item):
  302.                 putenv(key, item)
  303.                 self.data[key.upper()] = item
  304.             def __getitem__(self, key):
  305.                 return self.data[key.upper()]
  306.             def __delitem__(self, key):
  307.                 del self.data[key.upper()]
  308.             def has_key(self, key):
  309.                 return self.data.has_key(key.upper())
  310.             def get(self, key, failobj=None):
  311.                 return self.data.get(key.upper(), failobj)
  312.             def update(self, dict):
  313.                 for k, v in dict.items():
  314.                     self[k] = v
  315.  
  316.     else:  # Where Env Var Names Can Be Mixed Case
  317.         class _Environ(UserDict.UserDict):
  318.             def __init__(self, environ):
  319.                 UserDict.UserDict.__init__(self)
  320.                 self.data = environ
  321.             def __setitem__(self, key, item):
  322.                 putenv(key, item)
  323.                 self.data[key] = item
  324.             def update(self, dict):
  325.                 for k, v in dict.items():
  326.                     self[k] = v
  327.  
  328.     environ = _Environ(environ)
  329.  
  330. def getenv(key, default=None):
  331.     """Get an environment variable, return None if it doesn't exist.
  332.  
  333.     The optional second argument can specify an alternate default."""
  334.     return environ.get(key, default)
  335.  
  336. def _exists(name):
  337.     try:
  338.         eval(name)
  339.         return 1
  340.     except NameError:
  341.         return 0
  342.  
  343. # Supply spawn*() (probably only for Unix)
  344. if _exists("fork") and not _exists("spawnv") and _exists("execv"):
  345.  
  346.     P_WAIT = 0
  347.     P_NOWAIT = P_NOWAITO = 1
  348.  
  349.     # XXX Should we support P_DETACH?  I suppose it could fork()**2
  350.     # and close the std I/O streams.  Also, P_OVERLAY is the same
  351.     # as execv*()?
  352.  
  353.     def _spawnvef(mode, file, args, env, func):
  354.         # Internal helper; func is the exec*() function to use
  355.         pid = fork()
  356.         if not pid:
  357.             # Child
  358.             try:
  359.                 if env is None:
  360.                     func(file, args)
  361.                 else:
  362.                     func(file, args, env)
  363.             except:
  364.                 _exit(127)
  365.         else:
  366.             # Parent
  367.             if mode == P_NOWAIT:
  368.                 return pid # Caller is responsible for waiting!
  369.             while 1:
  370.                 wpid, sts = waitpid(pid, 0)
  371.                 if WIFSTOPPED(sts):
  372.                     continue
  373.                 elif WIFSIGNALED(sts):
  374.                     return -WTERMSIG(sts)
  375.                 elif WIFEXITED(sts):
  376.                     return WEXITSTATUS(sts)
  377.                 else:
  378.                     raise error, "Not stopped, signaled or exited???"
  379.  
  380.     def spawnv(mode, file, args):
  381.         """spawnv(mode, file, args) -> integer
  382.  
  383. Execute file with arguments from args in a subprocess.
  384. If mode == P_NOWAIT return the pid of the process.
  385. If mode == P_WAIT return the process's exit code if it exits normally;
  386. otherwise return -SIG, where SIG is the signal that killed it. """   
  387.         return _spawnvef(mode, file, args, None, execv)
  388.  
  389.     def spawnve(mode, file, args, env):
  390.         """spawnve(mode, file, args, env) -> integer
  391.  
  392. Execute file with arguments from args in a subprocess with the
  393. specified environment.
  394. If mode == P_NOWAIT return the pid of the process.
  395. If mode == P_WAIT return the process's exit code if it exits normally;
  396. otherwise return -SIG, where SIG is the signal that killed it. """
  397.         return _spawnvef(mode, file, args, env, execve)
  398.  
  399.     # Note: spawnvp[e] is't currently supported on Windows
  400.  
  401.     def spawnvp(mode, file, args):
  402.         """spawnvp(mode, file, args) -> integer
  403.  
  404. Execute file (which is looked for along $PATH) with arguments from
  405. args in a subprocess.
  406. If mode == P_NOWAIT return the pid of the process.
  407. If mode == P_WAIT return the process's exit code if it exits normally;
  408. otherwise return -SIG, where SIG is the signal that killed it. """
  409.         return _spawnvef(mode, file, args, None, execvp)
  410.  
  411.     def spawnvpe(mode, file, args, env):
  412.         """spawnvpe(mode, file, args, env) -> integer
  413.  
  414. Execute file (which is looked for along $PATH) with arguments from
  415. args in a subprocess with the supplied environment.
  416. If mode == P_NOWAIT return the pid of the process.
  417. If mode == P_WAIT return the process's exit code if it exits normally;
  418. otherwise return -SIG, where SIG is the signal that killed it. """
  419.         return _spawnvef(mode, file, args, env, execvpe)
  420.  
  421. if _exists("spawnv"):
  422.     # These aren't supplied by the basic Windows code
  423.     # but can be easily implemented in Python
  424.  
  425.     def spawnl(mode, file, *args):
  426.         """spawnl(mode, file, *args) -> integer
  427.  
  428. Execute file with arguments from args in a subprocess.
  429. If mode == P_NOWAIT return the pid of the process.
  430. If mode == P_WAIT return the process's exit code if it exits normally;
  431. otherwise return -SIG, where SIG is the signal that killed it. """
  432.         return spawnv(mode, file, args)
  433.  
  434.     def spawnle(mode, file, *args):
  435.         """spawnle(mode, file, *args, env) -> integer
  436.  
  437. Execute file with arguments from args in a subprocess with the
  438. supplied environment.
  439. If mode == P_NOWAIT return the pid of the process.
  440. If mode == P_WAIT return the process's exit code if it exits normally;
  441. otherwise return -SIG, where SIG is the signal that killed it. """
  442.         env = args[-1]
  443.         return spawnve(mode, file, args[:-1], env)
  444.  
  445. if _exists("spawnvp"):
  446.     # At the moment, Windows doesn't implement spawnvp[e],
  447.     # so it won't have spawnlp[e] either.
  448.     def spawnlp(mode, file, *args):
  449.         """spawnlp(mode, file, *args, env) -> integer
  450.  
  451. Execute file (which is looked for along $PATH) with arguments from
  452. args in a subprocess with the supplied environment.
  453. If mode == P_NOWAIT return the pid of the process.
  454. If mode == P_WAIT return the process's exit code if it exits normally;
  455. otherwise return -SIG, where SIG is the signal that killed it. """
  456.         return spawnvp(mode, file, args)
  457.  
  458.     def spawnlpe(mode, file, *args):
  459.         """spawnlpe(mode, file, *args, env) -> integer
  460.  
  461. Execute file (which is looked for along $PATH) with arguments from
  462. args in a subprocess with the supplied environment.
  463. If mode == P_NOWAIT return the pid of the process.
  464. If mode == P_WAIT return the process's exit code if it exits normally;
  465. otherwise return -SIG, where SIG is the signal that killed it. """
  466.         env = args[-1]
  467.         return spawnvpe(mode, file, args[:-1], env)
  468.  
  469.  
  470. # Supply popen2 etc. (for Unix)
  471. if _exists("fork"):
  472.     if not _exists("popen2"):
  473.         def popen2(cmd, mode="t", bufsize=-1):
  474.             import popen2
  475.             stdout, stdin = popen2.popen2(cmd, bufsize)
  476.             return stdin, stdout
  477.  
  478.     if not _exists("popen3"):
  479.         def popen3(cmd, mode="t", bufsize=-1):
  480.             import popen2
  481.             stdout, stdin, stderr = popen2.popen3(cmd, bufsize)
  482.             return stdin, stdout, stderr
  483.  
  484.     if not _exists("popen4"):
  485.         def popen4(cmd, mode="t", bufsize=-1):
  486.             import popen2
  487.             stdout, stdin = popen2.popen4(cmd, bufsize)
  488.             return stdin, stdout
  489.