home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 June / maximum-cd-2009-06.iso / DiscContents / OOo_3.0.1_Win32Intel_install_wJRE_en-US.exe / openofficeorg1.cab / os.py < prev    next >
Encoding:
Python Source  |  2008-12-15  |  21.5 KB  |  674 lines

  1. r"""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, os2, mac, or ce, e.g. unlink, stat, etc.
  5.   - os.path is one of the modules posixpath, ntpath, or macpath
  6.   - os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
  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.extsep is the extension separator ('.' or '/')
  11.   - os.altsep is the alternate pathname separator (None or '/')
  12.   - os.pathsep is the component separator used in $PATH etc
  13.   - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  14.   - os.defpath is the default search path for executables
  15.  
  16. Programs that import and use 'os' stand a better chance of being
  17. portable between different platforms.  Of course, they must then
  18. only use functions that are defined by all platforms (e.g., unlink
  19. and opendir), and leave all pathname manipulation to os.path
  20. (e.g., split and join).
  21. """
  22.  
  23. #'
  24.  
  25. import sys
  26.  
  27. _names = sys.builtin_module_names
  28.  
  29. # Note:  more names are added to __all__ later.
  30. __all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
  31.            "defpath", "name", "path"]
  32.  
  33. def _get_exports_list(module):
  34.     try:
  35.         return list(module.__all__)
  36.     except AttributeError:
  37.         return [n for n in dir(module) if n[0] != '_']
  38.  
  39. if 'mingw32' in _names:
  40.     name = 'nt'
  41.     linesep = '\r\n'
  42.     from posix import *
  43.     try:
  44.         from posix import _exit
  45.     except ImportError:
  46.         pass
  47.     import ntpath as path
  48.  
  49.     import posix
  50.     __all__.extend(_get_exports_list(posix))
  51.     del posix
  52.  
  53. elif 'posix' in _names:
  54.     name = 'posix'
  55.     linesep = '\n'
  56.     from posix import *
  57.     try:
  58.         from posix import _exit
  59.     except ImportError:
  60.         pass
  61.     import posixpath as path
  62.  
  63.     import posix
  64.     __all__.extend(_get_exports_list(posix))
  65.     del posix
  66.  
  67. elif 'nt' in _names:
  68.     name = 'nt'
  69.     linesep = '\r\n'
  70.     from nt import *
  71.     try:
  72.         from nt import _exit
  73.     except ImportError:
  74.         pass
  75.     import ntpath as path
  76.  
  77.     import nt
  78.     __all__.extend(_get_exports_list(nt))
  79.     del nt
  80.  
  81. elif 'os2' in _names:
  82.     name = 'os2'
  83.     linesep = '\r\n'
  84.     from os2 import *
  85.     try:
  86.         from os2 import _exit
  87.     except ImportError:
  88.         pass
  89.     if sys.version.find('EMX GCC') == -1:
  90.         import ntpath as path
  91.     else:
  92.         import os2emxpath as path
  93.  
  94.     import os2
  95.     __all__.extend(_get_exports_list(os2))
  96.     del os2
  97.  
  98. elif 'mac' in _names:
  99.     name = 'mac'
  100.     linesep = '\r'
  101.     from mac import *
  102.     try:
  103.         from mac import _exit
  104.     except ImportError:
  105.         pass
  106.     import macpath as path
  107.  
  108.     import mac
  109.     __all__.extend(_get_exports_list(mac))
  110.     del mac
  111.  
  112. elif 'ce' in _names:
  113.     name = 'ce'
  114.     linesep = '\r\n'
  115.     from ce import *
  116.     try:
  117.         from ce import _exit
  118.     except ImportError:
  119.         pass
  120.     # We can use the standard Windows path.
  121.     import ntpath as path
  122.  
  123.     import ce
  124.     __all__.extend(_get_exports_list(ce))
  125.     del ce
  126.  
  127. elif 'riscos' in _names:
  128.     name = 'riscos'
  129.     linesep = '\n'
  130.     from riscos import *
  131.     try:
  132.         from riscos import _exit
  133.     except ImportError:
  134.         pass
  135.     import riscospath as path
  136.  
  137.     import riscos
  138.     __all__.extend(_get_exports_list(riscos))
  139.     del riscos
  140.  
  141. else:
  142.     raise ImportError, 'no os specific module found'
  143.  
  144. sys.modules['os.path'] = path
  145. from os.path import curdir, pardir, sep, pathsep, defpath, extsep, altsep
  146.  
  147. del _names
  148.  
  149. #'
  150.  
  151. # Super directory utilities.
  152. # (Inspired by Eric Raymond; the doc strings are mostly his)
  153.  
  154. def makedirs(name, mode=0777):
  155.     """makedirs(path [, mode=0777])
  156.  
  157.     Super-mkdir; create a leaf directory and all intermediate ones.
  158.     Works like mkdir, except that any intermediate path segment (not
  159.     just the rightmost) will be created if it does not exist.  This is
  160.     recursive.
  161.  
  162.     """
  163.     head, tail = path.split(name)
  164.     if not tail:
  165.         head, tail = path.split(head)
  166.     if head and tail and not path.exists(head):
  167.         makedirs(head, mode)
  168.     mkdir(name, mode)
  169.  
  170. def removedirs(name):
  171.     """removedirs(path)
  172.  
  173.     Super-rmdir; remove a leaf directory and empty all intermediate
  174.     ones.  Works like rmdir except that, if the leaf directory is
  175.     successfully removed, directories corresponding to rightmost path
  176.     segments will be pruned away until either the whole path is
  177.     consumed or an error occurs.  Errors during this latter phase are
  178.     ignored -- they generally mean that a directory was not empty.
  179.  
  180.     """
  181.     rmdir(name)
  182.     head, tail = path.split(name)
  183.     if not tail:
  184.         head, tail = path.split(head)
  185.     while head and tail:
  186.         try:
  187.             rmdir(head)
  188.         except error:
  189.             break
  190.         head, tail = path.split(head)
  191.  
  192. def renames(old, new):
  193.     """renames(old, new)
  194.  
  195.     Super-rename; create directories as necessary and delete any left
  196.     empty.  Works like rename, except creation of any intermediate
  197.     directories needed to make the new pathname good is attempted
  198.     first.  After the rename, directories corresponding to rightmost
  199.     path segments of the old name will be pruned way until either the
  200.     whole path is consumed or a nonempty directory is found.
  201.  
  202.     Note: this function can fail with the new directory structure made
  203.     if you lack permissions needed to unlink the leaf directory or
  204.     file.
  205.  
  206.     """
  207.     head, tail = path.split(new)
  208.     if head and tail and not path.exists(head):
  209.         makedirs(head)
  210.     rename(old, new)
  211.     head, tail = path.split(old)
  212.     if head and tail:
  213.         try:
  214.             removedirs(head)
  215.         except error:
  216.             pass
  217.  
  218. __all__.extend(["makedirs", "removedirs", "renames"])
  219.  
  220. def walk(top, topdown=True, onerror=None):
  221.     """Directory tree generator.
  222.  
  223.     For each directory in the directory tree rooted at top (including top
  224.     itself, but excluding '.' and '..'), yields a 3-tuple
  225.  
  226.         dirpath, dirnames, filenames
  227.  
  228.     dirpath is a string, the path to the directory.  dirnames is a list of
  229.     the names of the subdirectories in dirpath (excluding '.' and '..').
  230.     filenames is a list of the names of the non-directory files in dirpath.
  231.     Note that the names in the lists are just names, with no path components.
  232.     To get a full path (which begins with top) to a file or directory in
  233.     dirpath, do os.path.join(dirpath, name).
  234.  
  235.     If optional arg 'topdown' is true or not specified, the triple for a
  236.     directory is generated before the triples for any of its subdirectories
  237.     (directories are generated top down).  If topdown is false, the triple
  238.     for a directory is generated after the triples for all of its
  239.     subdirectories (directories are generated bottom up).
  240.  
  241.     When topdown is true, the caller can modify the dirnames list in-place
  242.     (e.g., via del or slice assignment), and walk will only recurse into the
  243.     subdirectories whose names remain in dirnames; this can be used to prune
  244.     the search, or to impose a specific order of visiting.  Modifying
  245.     dirnames when topdown is false is ineffective, since the directories in
  246.     dirnames have already been generated by the time dirnames itself is
  247.     generated.
  248.  
  249.     By default errors from the os.listdir() call are ignored.  If
  250.     optional arg 'onerror' is specified, it should be a function; it
  251.     will be called with one argument, an os.error instance.  It can
  252.     report the error to continue with the walk, or raise the exception
  253.     to abort the walk.  Note that the filename is available as the
  254.     filename attribute of the exception object.
  255.  
  256.     Caution:  if you pass a relative pathname for top, don't change the
  257.     current working directory between resumptions of walk.  walk never
  258.     changes the current directory, and assumes that the client doesn't
  259.     either.
  260.  
  261.     Example:
  262.  
  263.     from os.path import join, getsize
  264.     for root, dirs, files in walk('python/Lib/email'):
  265.         print root, "consumes",
  266.         print sum([getsize(join(root, name)) for name in files]),
  267.         print "bytes in", len(files), "non-directory files"
  268.         if 'CVS' in dirs:
  269.             dirs.remove('CVS')  # don't visit CVS directories
  270.     """
  271.  
  272.     from os.path import join, isdir, islink
  273.  
  274.     # We may not have read permission for top, in which case we can't
  275.     # get a list of the files the directory contains.  os.path.walk
  276.     # always suppressed the exception then, rather than blow up for a
  277.     # minor reason when (say) a thousand readable directories are still
  278.     # left to visit.  That logic is copied here.
  279.     try:
  280.         # Note that listdir and error are globals in this module due
  281.         # to earlier import-*.
  282.         names = listdir(top)
  283.     except error, err:
  284.         if onerror is not None:
  285.             onerror(err)
  286.         return
  287.  
  288.     dirs, nondirs = [], []
  289.     for name in names:
  290.         if isdir(join(top, name)):
  291.             dirs.append(name)
  292.         else:
  293.             nondirs.append(name)
  294.  
  295.     if topdown:
  296.         yield top, dirs, nondirs
  297.     for name in dirs:
  298.         path = join(top, name)
  299.         if not islink(path):
  300.             for x in walk(path, topdown, onerror):
  301.                 yield x
  302.     if not topdown:
  303.         yield top, dirs, nondirs
  304.  
  305. __all__.append("walk")
  306.  
  307. # Make sure os.environ exists, at least
  308. try:
  309.     environ
  310. except NameError:
  311.     environ = {}
  312.  
  313. def execl(file, *args):
  314.     """execl(file, *args)
  315.  
  316.     Execute the executable file with argument list args, replacing the
  317.     current process. """
  318.     execv(file, args)
  319.  
  320. def execle(file, *args):
  321.     """execle(file, *args, env)
  322.  
  323.     Execute the executable file with argument list args and
  324.     environment env, replacing the current process. """
  325.     env = args[-1]
  326.     execve(file, args[:-1], env)
  327.  
  328. def execlp(file, *args):
  329.     """execlp(file, *args)
  330.  
  331.     Execute the executable file (which is searched for along $PATH)
  332.     with argument list args, replacing the current process. """
  333.     execvp(file, args)
  334.  
  335. def execlpe(file, *args):
  336.     """execlpe(file, *args, env)
  337.  
  338.     Execute the executable file (which is searched for along $PATH)
  339.     with argument list args and environment env, replacing the current
  340.     process. """
  341.     env = args[-1]
  342.     execvpe(file, args[:-1], env)
  343.  
  344. def execvp(file, args):
  345.     """execp(file, args)
  346.  
  347.     Execute the executable file (which is searched for along $PATH)
  348.     with argument list args, replacing the current process.
  349.     args may be a list or tuple of strings. """
  350.     _execvpe(file, args)
  351.  
  352. def execvpe(file, args, env):
  353.     """execvpe(file, args, env)
  354.  
  355.     Execute the executable file (which is searched for along $PATH)
  356.     with argument list args and environment env , replacing the
  357.     current process.
  358.     args may be a list or tuple of strings. """
  359.     _execvpe(file, args, env)
  360.  
  361. __all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
  362.  
  363. def _execvpe(file, args, env=None):
  364.     from errno import ENOENT, ENOTDIR
  365.  
  366.     if env is not None:
  367.         func = execve
  368.         argrest = (args, env)
  369.     else:
  370.         func = execv
  371.         argrest = (args,)
  372.         env = environ
  373.  
  374.     head, tail = path.split(file)
  375.     if head:
  376.         func(file, *argrest)
  377.         return
  378.     if 'PATH' in env:
  379.         envpath = env['PATH']
  380.     else:
  381.         envpath = defpath
  382.     PATH = envpath.split(pathsep)
  383.     saved_exc = None
  384.     saved_tb = None
  385.     for dir in PATH:
  386.         fullname = path.join(dir, file)
  387.         try:
  388.             func(fullname, *argrest)
  389.         except error, e:
  390.             tb = sys.exc_info()[2]
  391.             if (e.errno != ENOENT and e.errno != ENOTDIR
  392.                 and saved_exc is None):
  393.                 saved_exc = e
  394.                 saved_tb = tb
  395.     if saved_exc:
  396.         raise error, saved_exc, saved_tb
  397.     raise error, e, tb
  398.  
  399. # Change environ to automatically call putenv() if it exists
  400. try:
  401.     # This will fail if there's no putenv
  402.     putenv
  403. except NameError:
  404.     pass
  405. else:
  406.     import UserDict
  407.  
  408.     # Fake unsetenv() for Windows
  409.     # not sure about os2 here but
  410.     # I'm guessing they are the same.
  411.  
  412.     if name in ('os2', 'nt'):
  413.         def unsetenv(key):
  414.             putenv(key, "")
  415.  
  416.     if name == "riscos":
  417.         # On RISC OS, all env access goes through getenv and putenv
  418.         from riscosenviron import _Environ
  419.     elif name in ('os2', 'nt'):  # Where Env Var Names Must Be UPPERCASE
  420.         # But we store them as upper case
  421.         class _Environ(UserDict.IterableUserDict):
  422.             def __init__(self, environ):
  423.                 UserDict.UserDict.__init__(self)
  424.                 data = self.data
  425.                 for k, v in environ.items():
  426.                     data[k.upper()] = v
  427.             def __setitem__(self, key, item):
  428.                 putenv(key, item)
  429.                 self.data[key.upper()] = item
  430.             def __getitem__(self, key):
  431.                 return self.data[key.upper()]
  432.             try:
  433.                 unsetenv
  434.             except NameError:
  435.                 def __delitem__(self, key):
  436.                     del self.data[key.upper()]
  437.             else:
  438.                 def __delitem__(self, key):
  439.                     unsetenv(key)
  440.                     del self.data[key.upper()]
  441.             def has_key(self, key):
  442.                 return key.upper() in self.data
  443.             def __contains__(self, key):
  444.                 return key.upper() in self.data
  445.             def get(self, key, failobj=None):
  446.                 return self.data.get(key.upper(), failobj)
  447.             def update(self, dict):
  448.                 for k, v in dict.items():
  449.                     self[k] = v
  450.             def copy(self):
  451.                 return dict(self)
  452.  
  453.     else:  # Where Env Var Names Can Be Mixed Case
  454.         class _Environ(UserDict.IterableUserDict):
  455.             def __init__(self, environ):
  456.                 UserDict.UserDict.__init__(self)
  457.                 self.data = environ
  458.             def __setitem__(self, key, item):
  459.                 putenv(key, item)
  460.                 self.data[key] = item
  461.             def update(self, dict):
  462.                 for k, v in dict.items():
  463.                     self[k] = v
  464.             try:
  465.                 unsetenv
  466.             except NameError:
  467.                 pass
  468.             else:
  469.                 def __delitem__(self, key):
  470.                     unsetenv(key)
  471.                     del self.data[key]
  472.             def copy(self):
  473.                 return dict(self)
  474.  
  475.  
  476.     environ = _Environ(environ)
  477.  
  478. def getenv(key, default=None):
  479.     """Get an environment variable, return None if it doesn't exist.
  480.     The optional second argument can specify an alternate default."""
  481.     return environ.get(key, default)
  482. __all__.append("getenv")
  483.  
  484. def _exists(name):
  485.     try:
  486.         eval(name)
  487.         return True
  488.     except NameError:
  489.         return False
  490.  
  491. # Supply spawn*() (probably only for Unix)
  492. if _exists("fork") and not _exists("spawnv") and _exists("execv"):
  493.  
  494.     P_WAIT = 0
  495.     P_NOWAIT = P_NOWAITO = 1
  496.  
  497.     # XXX Should we support P_DETACH?  I suppose it could fork()**2
  498.     # and close the std I/O streams.  Also, P_OVERLAY is the same
  499.     # as execv*()?
  500.  
  501.     def _spawnvef(mode, file, args, env, func):
  502.         # Internal helper; func is the exec*() function to use
  503.         pid = fork()
  504.         if not pid:
  505.             # Child
  506.             try:
  507.                 if env is None:
  508.                     func(file, args)
  509.                 else:
  510.                     func(file, args, env)
  511.             except:
  512.                 _exit(127)
  513.         else:
  514.             # Parent
  515.             if mode == P_NOWAIT:
  516.                 return pid # Caller is responsible for waiting!
  517.             while 1:
  518.                 wpid, sts = waitpid(pid, 0)
  519.                 if WIFSTOPPED(sts):
  520.                     continue
  521.                 elif WIFSIGNALED(sts):
  522.                     return -WTERMSIG(sts)
  523.                 elif WIFEXITED(sts):
  524.                     return WEXITSTATUS(sts)
  525.                 else:
  526.                     raise error, "Not stopped, signaled or exited???"
  527.  
  528.     def spawnv(mode, file, args):
  529.         """spawnv(mode, file, args) -> integer
  530.  
  531. Execute file with arguments from args in a subprocess.
  532. If mode == P_NOWAIT return the pid of the process.
  533. If mode == P_WAIT return the process's exit code if it exits normally;
  534. otherwise return -SIG, where SIG is the signal that killed it. """
  535.         return _spawnvef(mode, file, args, None, execv)
  536.  
  537.     def spawnve(mode, file, args, env):
  538.         """spawnve(mode, file, args, env) -> integer
  539.  
  540. Execute file with arguments from args in a subprocess with the
  541. specified environment.
  542. If mode == P_NOWAIT return the pid of the process.
  543. If mode == P_WAIT return the process's exit code if it exits normally;
  544. otherwise return -SIG, where SIG is the signal that killed it. """
  545.         return _spawnvef(mode, file, args, env, execve)
  546.  
  547.     # Note: spawnvp[e] is't currently supported on Windows
  548.  
  549.     def spawnvp(mode, file, args):
  550.         """spawnvp(mode, file, args) -> integer
  551.  
  552. Execute file (which is looked for along $PATH) with arguments from
  553. args in a subprocess.
  554. If mode == P_NOWAIT return the pid of the process.
  555. If mode == P_WAIT return the process's exit code if it exits normally;
  556. otherwise return -SIG, where SIG is the signal that killed it. """
  557.         return _spawnvef(mode, file, args, None, execvp)
  558.  
  559.     def spawnvpe(mode, file, args, env):
  560.         """spawnvpe(mode, file, args, env) -> integer
  561.  
  562. Execute file (which is looked for along $PATH) with arguments from
  563. args in a subprocess with the supplied environment.
  564. If mode == P_NOWAIT return the pid of the process.
  565. If mode == P_WAIT return the process's exit code if it exits normally;
  566. otherwise return -SIG, where SIG is the signal that killed it. """
  567.         return _spawnvef(mode, file, args, env, execvpe)
  568.  
  569. if _exists("spawnv"):
  570.     # These aren't supplied by the basic Windows code
  571.     # but can be easily implemented in Python
  572.  
  573.     def spawnl(mode, file, *args):
  574.         """spawnl(mode, file, *args) -> integer
  575.  
  576. Execute file with arguments from args in a subprocess.
  577. If mode == P_NOWAIT return the pid of the process.
  578. If mode == P_WAIT return the process's exit code if it exits normally;
  579. otherwise return -SIG, where SIG is the signal that killed it. """
  580.         return spawnv(mode, file, args)
  581.  
  582.     def spawnle(mode, file, *args):
  583.         """spawnle(mode, file, *args, env) -> integer
  584.  
  585. Execute file with arguments from args in a subprocess with the
  586. supplied environment.
  587. If mode == P_NOWAIT return the pid of the process.
  588. If mode == P_WAIT return the process's exit code if it exits normally;
  589. otherwise return -SIG, where SIG is the signal that killed it. """
  590.         env = args[-1]
  591.         return spawnve(mode, file, args[:-1], env)
  592.  
  593.  
  594.     __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])
  595.  
  596.  
  597. if _exists("spawnvp"):
  598.     # At the moment, Windows doesn't implement spawnvp[e],
  599.     # so it won't have spawnlp[e] either.
  600.     def spawnlp(mode, file, *args):
  601.         """spawnlp(mode, file, *args) -> integer
  602.  
  603. Execute file (which is looked for along $PATH) with arguments from
  604. args in a subprocess with the supplied environment.
  605. If mode == P_NOWAIT return the pid of the process.
  606. If mode == P_WAIT return the process's exit code if it exits normally;
  607. otherwise return -SIG, where SIG is the signal that killed it. """
  608.         return spawnvp(mode, file, args)
  609.  
  610.     def spawnlpe(mode, file, *args):
  611.         """spawnlpe(mode, file, *args, env) -> integer
  612.  
  613. Execute file (which is looked for along $PATH) with arguments from
  614. args in a subprocess with the supplied environment.
  615. If mode == P_NOWAIT return the pid of the process.
  616. If mode == P_WAIT return the process's exit code if it exits normally;
  617. otherwise return -SIG, where SIG is the signal that killed it. """
  618.         env = args[-1]
  619.         return spawnvpe(mode, file, args[:-1], env)
  620.  
  621.  
  622.     __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])
  623.  
  624.  
  625. # Supply popen2 etc. (for Unix)
  626. if _exists("fork"):
  627.     if not _exists("popen2"):
  628.         def popen2(cmd, mode="t", bufsize=-1):
  629.             import popen2
  630.             stdout, stdin = popen2.popen2(cmd, bufsize)
  631.             return stdin, stdout
  632.         __all__.append("popen2")
  633.  
  634.     if not _exists("popen3"):
  635.         def popen3(cmd, mode="t", bufsize=-1):
  636.             import popen2
  637.             stdout, stdin, stderr = popen2.popen3(cmd, bufsize)
  638.             return stdin, stdout, stderr
  639.         __all__.append("popen3")
  640.  
  641.     if not _exists("popen4"):
  642.         def popen4(cmd, mode="t", bufsize=-1):
  643.             import popen2
  644.             stdout, stdin = popen2.popen4(cmd, bufsize)
  645.             return stdin, stdout
  646.         __all__.append("popen4")
  647.  
  648. import copy_reg as _copy_reg
  649.  
  650. def _make_stat_result(tup, dict):
  651.     return stat_result(tup, dict)
  652.  
  653. def _pickle_stat_result(sr):
  654.     (type, args) = sr.__reduce__()
  655.     return (_make_stat_result, args)
  656.  
  657. try:
  658.     _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)
  659. except NameError: # stat_result may not exist
  660.     pass
  661.  
  662. def _make_statvfs_result(tup, dict):
  663.     return statvfs_result(tup, dict)
  664.  
  665. def _pickle_statvfs_result(sr):
  666.     (type, args) = sr.__reduce__()
  667.     return (_make_statvfs_result, args)
  668.  
  669. try:
  670.     _copy_reg.pickle(statvfs_result, _pickle_statvfs_result,
  671.                      _make_statvfs_result)
  672. except NameError: # statvfs_result may not exist
  673.     pass
  674.