PyXR

c:\python24\lib \ os.py



0001 r"""OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
0002 
0003 This exports:
0004   - all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
0005   - os.path is one of the modules posixpath, ntpath, or macpath
0006   - os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
0007   - os.curdir is a string representing the current directory ('.' or ':')
0008   - os.pardir is a string representing the parent directory ('..' or '::')
0009   - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
0010   - os.extsep is the extension separator ('.' or '/')
0011   - os.altsep is the alternate pathname separator (None or '/')
0012   - os.pathsep is the component separator used in $PATH etc
0013   - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
0014   - os.defpath is the default search path for executables
0015   - os.devnull is the file path of the null device ('/dev/null', etc.)
0016 
0017 Programs that import and use 'os' stand a better chance of being
0018 portable between different platforms.  Of course, they must then
0019 only use functions that are defined by all platforms (e.g., unlink
0020 and opendir), and leave all pathname manipulation to os.path
0021 (e.g., split and join).
0022 """
0023 
0024 #'
0025 
0026 import sys
0027 
0028 _names = sys.builtin_module_names
0029 
0030 # Note:  more names are added to __all__ later.
0031 __all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
0032            "defpath", "name", "path", "devnull"]
0033 
0034 def _get_exports_list(module):
0035     try:
0036         return list(module.__all__)
0037     except AttributeError:
0038         return [n for n in dir(module) if n[0] != '_']
0039 
0040 if 'posix' in _names:
0041     name = 'posix'
0042     linesep = '\n'
0043     from posix import *
0044     try:
0045         from posix import _exit
0046     except ImportError:
0047         pass
0048     import posixpath as path
0049 
0050     import posix
0051     __all__.extend(_get_exports_list(posix))
0052     del posix
0053 
0054 elif 'nt' in _names:
0055     name = 'nt'
0056     linesep = '\r\n'
0057     from nt import *
0058     try:
0059         from nt import _exit
0060     except ImportError:
0061         pass
0062     import ntpath as path
0063 
0064     import nt
0065     __all__.extend(_get_exports_list(nt))
0066     del nt
0067 
0068 elif 'os2' in _names:
0069     name = 'os2'
0070     linesep = '\r\n'
0071     from os2 import *
0072     try:
0073         from os2 import _exit
0074     except ImportError:
0075         pass
0076     if sys.version.find('EMX GCC') == -1:
0077         import ntpath as path
0078     else:
0079         import os2emxpath as path
0080         from _emx_link import link
0081 
0082     import os2
0083     __all__.extend(_get_exports_list(os2))
0084     del os2
0085 
0086 elif 'mac' in _names:
0087     name = 'mac'
0088     linesep = '\r'
0089     from mac import *
0090     try:
0091         from mac import _exit
0092     except ImportError:
0093         pass
0094     import macpath as path
0095 
0096     import mac
0097     __all__.extend(_get_exports_list(mac))
0098     del mac
0099 
0100 elif 'ce' in _names:
0101     name = 'ce'
0102     linesep = '\r\n'
0103     from ce import *
0104     try:
0105         from ce import _exit
0106     except ImportError:
0107         pass
0108     # We can use the standard Windows path.
0109     import ntpath as path
0110 
0111     import ce
0112     __all__.extend(_get_exports_list(ce))
0113     del ce
0114 
0115 elif 'riscos' in _names:
0116     name = 'riscos'
0117     linesep = '\n'
0118     from riscos import *
0119     try:
0120         from riscos import _exit
0121     except ImportError:
0122         pass
0123     import riscospath as path
0124 
0125     import riscos
0126     __all__.extend(_get_exports_list(riscos))
0127     del riscos
0128 
0129 else:
0130     raise ImportError, 'no os specific module found'
0131 
0132 sys.modules['os.path'] = path
0133 from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
0134     devnull)
0135 
0136 del _names
0137 
0138 #'
0139 
0140 # Super directory utilities.
0141 # (Inspired by Eric Raymond; the doc strings are mostly his)
0142 
0143 def makedirs(name, mode=0777):
0144     """makedirs(path [, mode=0777])
0145 
0146     Super-mkdir; create a leaf directory and all intermediate ones.
0147     Works like mkdir, except that any intermediate path segment (not
0148     just the rightmost) will be created if it does not exist.  This is
0149     recursive.
0150 
0151     """
0152     head, tail = path.split(name)
0153     if not tail:
0154         head, tail = path.split(head)
0155     if head and tail and not path.exists(head):
0156         makedirs(head, mode)
0157         if tail == curdir:           # xxx/newdir/. exists if xxx/newdir exists
0158             return
0159     mkdir(name, mode)
0160 
0161 def removedirs(name):
0162     """removedirs(path)
0163 
0164     Super-rmdir; remove a leaf directory and empty all intermediate
0165     ones.  Works like rmdir except that, if the leaf directory is
0166     successfully removed, directories corresponding to rightmost path
0167     segments will be pruned away until either the whole path is
0168     consumed or an error occurs.  Errors during this latter phase are
0169     ignored -- they generally mean that a directory was not empty.
0170 
0171     """
0172     rmdir(name)
0173     head, tail = path.split(name)
0174     if not tail:
0175         head, tail = path.split(head)
0176     while head and tail:
0177         try:
0178             rmdir(head)
0179         except error:
0180             break
0181         head, tail = path.split(head)
0182 
0183 def renames(old, new):
0184     """renames(old, new)
0185 
0186     Super-rename; create directories as necessary and delete any left
0187     empty.  Works like rename, except creation of any intermediate
0188     directories needed to make the new pathname good is attempted
0189     first.  After the rename, directories corresponding to rightmost
0190     path segments of the old name will be pruned way until either the
0191     whole path is consumed or a nonempty directory is found.
0192 
0193     Note: this function can fail with the new directory structure made
0194     if you lack permissions needed to unlink the leaf directory or
0195     file.
0196 
0197     """
0198     head, tail = path.split(new)
0199     if head and tail and not path.exists(head):
0200         makedirs(head)
0201     rename(old, new)
0202     head, tail = path.split(old)
0203     if head and tail:
0204         try:
0205             removedirs(head)
0206         except error:
0207             pass
0208 
0209 __all__.extend(["makedirs", "removedirs", "renames"])
0210 
0211 def walk(top, topdown=True, onerror=None):
0212     """Directory tree generator.
0213 
0214     For each directory in the directory tree rooted at top (including top
0215     itself, but excluding '.' and '..'), yields a 3-tuple
0216 
0217         dirpath, dirnames, filenames
0218 
0219     dirpath is a string, the path to the directory.  dirnames is a list of
0220     the names of the subdirectories in dirpath (excluding '.' and '..').
0221     filenames is a list of the names of the non-directory files in dirpath.
0222     Note that the names in the lists are just names, with no path components.
0223     To get a full path (which begins with top) to a file or directory in
0224     dirpath, do os.path.join(dirpath, name).
0225 
0226     If optional arg 'topdown' is true or not specified, the triple for a
0227     directory is generated before the triples for any of its subdirectories
0228     (directories are generated top down).  If topdown is false, the triple
0229     for a directory is generated after the triples for all of its
0230     subdirectories (directories are generated bottom up).
0231 
0232     When topdown is true, the caller can modify the dirnames list in-place
0233     (e.g., via del or slice assignment), and walk will only recurse into the
0234     subdirectories whose names remain in dirnames; this can be used to prune
0235     the search, or to impose a specific order of visiting.  Modifying
0236     dirnames when topdown is false is ineffective, since the directories in
0237     dirnames have already been generated by the time dirnames itself is
0238     generated.
0239 
0240     By default errors from the os.listdir() call are ignored.  If
0241     optional arg 'onerror' is specified, it should be a function; it
0242     will be called with one argument, an os.error instance.  It can
0243     report the error to continue with the walk, or raise the exception
0244     to abort the walk.  Note that the filename is available as the
0245     filename attribute of the exception object.
0246 
0247     Caution:  if you pass a relative pathname for top, don't change the
0248     current working directory between resumptions of walk.  walk never
0249     changes the current directory, and assumes that the client doesn't
0250     either.
0251 
0252     Example:
0253 
0254     from os.path import join, getsize
0255     for root, dirs, files in walk('python/Lib/email'):
0256         print root, "consumes",
0257         print sum([getsize(join(root, name)) for name in files]),
0258         print "bytes in", len(files), "non-directory files"
0259         if 'CVS' in dirs:
0260             dirs.remove('CVS')  # don't visit CVS directories
0261     """
0262 
0263     from os.path import join, isdir, islink
0264 
0265     # We may not have read permission for top, in which case we can't
0266     # get a list of the files the directory contains.  os.path.walk
0267     # always suppressed the exception then, rather than blow up for a
0268     # minor reason when (say) a thousand readable directories are still
0269     # left to visit.  That logic is copied here.
0270     try:
0271         # Note that listdir and error are globals in this module due
0272         # to earlier import-*.
0273         names = listdir(top)
0274     except error, err:
0275         if onerror is not None:
0276             onerror(err)
0277         return
0278 
0279     dirs, nondirs = [], []
0280     for name in names:
0281         if isdir(join(top, name)):
0282             dirs.append(name)
0283         else:
0284             nondirs.append(name)
0285 
0286     if topdown:
0287         yield top, dirs, nondirs
0288     for name in dirs:
0289         path = join(top, name)
0290         if not islink(path):
0291             for x in walk(path, topdown, onerror):
0292                 yield x
0293     if not topdown:
0294         yield top, dirs, nondirs
0295 
0296 __all__.append("walk")
0297 
0298 # Make sure os.environ exists, at least
0299 try:
0300     environ
0301 except NameError:
0302     environ = {}
0303 
0304 def execl(file, *args):
0305     """execl(file, *args)
0306 
0307     Execute the executable file with argument list args, replacing the
0308     current process. """
0309     execv(file, args)
0310 
0311 def execle(file, *args):
0312     """execle(file, *args, env)
0313 
0314     Execute the executable file with argument list args and
0315     environment env, replacing the current process. """
0316     env = args[-1]
0317     execve(file, args[:-1], env)
0318 
0319 def execlp(file, *args):
0320     """execlp(file, *args)
0321 
0322     Execute the executable file (which is searched for along $PATH)
0323     with argument list args, replacing the current process. """
0324     execvp(file, args)
0325 
0326 def execlpe(file, *args):
0327     """execlpe(file, *args, env)
0328 
0329     Execute the executable file (which is searched for along $PATH)
0330     with argument list args and environment env, replacing the current
0331     process. """
0332     env = args[-1]
0333     execvpe(file, args[:-1], env)
0334 
0335 def execvp(file, args):
0336     """execp(file, args)
0337 
0338     Execute the executable file (which is searched for along $PATH)
0339     with argument list args, replacing the current process.
0340     args may be a list or tuple of strings. """
0341     _execvpe(file, args)
0342 
0343 def execvpe(file, args, env):
0344     """execvpe(file, args, env)
0345 
0346     Execute the executable file (which is searched for along $PATH)
0347     with argument list args and environment env , replacing the
0348     current process.
0349     args may be a list or tuple of strings. """
0350     _execvpe(file, args, env)
0351 
0352 __all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
0353 
0354 def _execvpe(file, args, env=None):
0355     from errno import ENOENT, ENOTDIR
0356 
0357     if env is not None:
0358         func = execve
0359         argrest = (args, env)
0360     else:
0361         func = execv
0362         argrest = (args,)
0363         env = environ
0364 
0365     head, tail = path.split(file)
0366     if head:
0367         func(file, *argrest)
0368         return
0369     if 'PATH' in env:
0370         envpath = env['PATH']
0371     else:
0372         envpath = defpath
0373     PATH = envpath.split(pathsep)
0374     saved_exc = None
0375     saved_tb = None
0376     for dir in PATH:
0377         fullname = path.join(dir, file)
0378         try:
0379             func(fullname, *argrest)
0380         except error, e:
0381             tb = sys.exc_info()[2]
0382             if (e.errno != ENOENT and e.errno != ENOTDIR
0383                 and saved_exc is None):
0384                 saved_exc = e
0385                 saved_tb = tb
0386     if saved_exc:
0387         raise error, saved_exc, saved_tb
0388     raise error, e, tb
0389 
0390 # Change environ to automatically call putenv() if it exists
0391 try:
0392     # This will fail if there's no putenv
0393     putenv
0394 except NameError:
0395     pass
0396 else:
0397     import UserDict
0398 
0399     # Fake unsetenv() for Windows
0400     # not sure about os2 here but
0401     # I'm guessing they are the same.
0402 
0403     if name in ('os2', 'nt'):
0404         def unsetenv(key):
0405             putenv(key, "")
0406 
0407     if name == "riscos":
0408         # On RISC OS, all env access goes through getenv and putenv
0409         from riscosenviron import _Environ
0410     elif name in ('os2', 'nt'):  # Where Env Var Names Must Be UPPERCASE
0411         # But we store them as upper case
0412         class _Environ(UserDict.IterableUserDict):
0413             def __init__(self, environ):
0414                 UserDict.UserDict.__init__(self)
0415                 data = self.data
0416                 for k, v in environ.items():
0417                     data[k.upper()] = v
0418             def __setitem__(self, key, item):
0419                 putenv(key, item)
0420                 self.data[key.upper()] = item
0421             def __getitem__(self, key):
0422                 return self.data[key.upper()]
0423             try:
0424                 unsetenv
0425             except NameError:
0426                 def __delitem__(self, key):
0427                     del self.data[key.upper()]
0428             else:
0429                 def __delitem__(self, key):
0430                     unsetenv(key)
0431                     del self.data[key.upper()]
0432             def has_key(self, key):
0433                 return key.upper() in self.data
0434             def __contains__(self, key):
0435                 return key.upper() in self.data
0436             def get(self, key, failobj=None):
0437                 return self.data.get(key.upper(), failobj)
0438             def copy(self):
0439                 return dict(self)
0440 
0441     else:  # Where Env Var Names Can Be Mixed Case
0442         class _Environ(UserDict.IterableUserDict):
0443             def __init__(self, environ):
0444                 UserDict.UserDict.__init__(self)
0445                 self.data = environ
0446             def __setitem__(self, key, item):
0447                 putenv(key, item)
0448                 self.data[key] = item
0449             try:
0450                 unsetenv
0451             except NameError:
0452                 pass
0453             else:
0454                 def __delitem__(self, key):
0455                     unsetenv(key)
0456                     del self.data[key]
0457             def copy(self):
0458                 return dict(self)
0459 
0460 
0461     environ = _Environ(environ)
0462 
0463 def getenv(key, default=None):
0464     """Get an environment variable, return None if it doesn't exist.
0465     The optional second argument can specify an alternate default."""
0466     return environ.get(key, default)
0467 __all__.append("getenv")
0468 
0469 def _exists(name):
0470     try:
0471         eval(name)
0472         return True
0473     except NameError:
0474         return False
0475 
0476 # Supply spawn*() (probably only for Unix)
0477 if _exists("fork") and not _exists("spawnv") and _exists("execv"):
0478 
0479     P_WAIT = 0
0480     P_NOWAIT = P_NOWAITO = 1
0481 
0482     # XXX Should we support P_DETACH?  I suppose it could fork()**2
0483     # and close the std I/O streams.  Also, P_OVERLAY is the same
0484     # as execv*()?
0485 
0486     def _spawnvef(mode, file, args, env, func):
0487         # Internal helper; func is the exec*() function to use
0488         pid = fork()
0489         if not pid:
0490             # Child
0491             try:
0492                 if env is None:
0493                     func(file, args)
0494                 else:
0495                     func(file, args, env)
0496             except:
0497                 _exit(127)
0498         else:
0499             # Parent
0500             if mode == P_NOWAIT:
0501                 return pid # Caller is responsible for waiting!
0502             while 1:
0503                 wpid, sts = waitpid(pid, 0)
0504                 if WIFSTOPPED(sts):
0505                     continue
0506                 elif WIFSIGNALED(sts):
0507                     return -WTERMSIG(sts)
0508                 elif WIFEXITED(sts):
0509                     return WEXITSTATUS(sts)
0510                 else:
0511                     raise error, "Not stopped, signaled or exited???"
0512 
0513     def spawnv(mode, file, args):
0514         """spawnv(mode, file, args) -> integer
0515 
0516 Execute file with arguments from args in a subprocess.
0517 If mode == P_NOWAIT return the pid of the process.
0518 If mode == P_WAIT return the process's exit code if it exits normally;
0519 otherwise return -SIG, where SIG is the signal that killed it. """
0520         return _spawnvef(mode, file, args, None, execv)
0521 
0522     def spawnve(mode, file, args, env):
0523         """spawnve(mode, file, args, env) -> integer
0524 
0525 Execute file with arguments from args in a subprocess with the
0526 specified environment.
0527 If mode == P_NOWAIT return the pid of the process.
0528 If mode == P_WAIT return the process's exit code if it exits normally;
0529 otherwise return -SIG, where SIG is the signal that killed it. """
0530         return _spawnvef(mode, file, args, env, execve)
0531 
0532     # Note: spawnvp[e] is't currently supported on Windows
0533 
0534     def spawnvp(mode, file, args):
0535         """spawnvp(mode, file, args) -> integer
0536 
0537 Execute file (which is looked for along $PATH) with arguments from
0538 args in a subprocess.
0539 If mode == P_NOWAIT return the pid of the process.
0540 If mode == P_WAIT return the process's exit code if it exits normally;
0541 otherwise return -SIG, where SIG is the signal that killed it. """
0542         return _spawnvef(mode, file, args, None, execvp)
0543 
0544     def spawnvpe(mode, file, args, env):
0545         """spawnvpe(mode, file, args, env) -> integer
0546 
0547 Execute file (which is looked for along $PATH) with arguments from
0548 args in a subprocess with the supplied environment.
0549 If mode == P_NOWAIT return the pid of the process.
0550 If mode == P_WAIT return the process's exit code if it exits normally;
0551 otherwise return -SIG, where SIG is the signal that killed it. """
0552         return _spawnvef(mode, file, args, env, execvpe)
0553 
0554 if _exists("spawnv"):
0555     # These aren't supplied by the basic Windows code
0556     # but can be easily implemented in Python
0557 
0558     def spawnl(mode, file, *args):
0559         """spawnl(mode, file, *args) -> integer
0560 
0561 Execute file with arguments from args in a subprocess.
0562 If mode == P_NOWAIT return the pid of the process.
0563 If mode == P_WAIT return the process's exit code if it exits normally;
0564 otherwise return -SIG, where SIG is the signal that killed it. """
0565         return spawnv(mode, file, args)
0566 
0567     def spawnle(mode, file, *args):
0568         """spawnle(mode, file, *args, env) -> integer
0569 
0570 Execute file with arguments from args in a subprocess with the
0571 supplied environment.
0572 If mode == P_NOWAIT return the pid of the process.
0573 If mode == P_WAIT return the process's exit code if it exits normally;
0574 otherwise return -SIG, where SIG is the signal that killed it. """
0575         env = args[-1]
0576         return spawnve(mode, file, args[:-1], env)
0577 
0578 
0579     __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])
0580 
0581 
0582 if _exists("spawnvp"):
0583     # At the moment, Windows doesn't implement spawnvp[e],
0584     # so it won't have spawnlp[e] either.
0585     def spawnlp(mode, file, *args):
0586         """spawnlp(mode, file, *args) -> integer
0587 
0588 Execute file (which is looked for along $PATH) with arguments from
0589 args in a subprocess with the supplied environment.
0590 If mode == P_NOWAIT return the pid of the process.
0591 If mode == P_WAIT return the process's exit code if it exits normally;
0592 otherwise return -SIG, where SIG is the signal that killed it. """
0593         return spawnvp(mode, file, args)
0594 
0595     def spawnlpe(mode, file, *args):
0596         """spawnlpe(mode, file, *args, env) -> integer
0597 
0598 Execute file (which is looked for along $PATH) with arguments from
0599 args in a subprocess with the supplied environment.
0600 If mode == P_NOWAIT return the pid of the process.
0601 If mode == P_WAIT return the process's exit code if it exits normally;
0602 otherwise return -SIG, where SIG is the signal that killed it. """
0603         env = args[-1]
0604         return spawnvpe(mode, file, args[:-1], env)
0605 
0606 
0607     __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])
0608 
0609 
0610 # Supply popen2 etc. (for Unix)
0611 if _exists("fork"):
0612     if not _exists("popen2"):
0613         def popen2(cmd, mode="t", bufsize=-1):
0614             """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'
0615             may be a sequence, in which case arguments will be passed directly to
0616             the program without shell intervention (as with os.spawnv()).  If 'cmd'
0617             is a string it will be passed to the shell (as with os.system()). If
0618             'bufsize' is specified, it sets the buffer size for the I/O pipes.  The
0619             file objects (child_stdin, child_stdout) are returned."""
0620             import popen2
0621             stdout, stdin = popen2.popen2(cmd, bufsize)
0622             return stdin, stdout
0623         __all__.append("popen2")
0624 
0625     if not _exists("popen3"):
0626         def popen3(cmd, mode="t", bufsize=-1):
0627             """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'
0628             may be a sequence, in which case arguments will be passed directly to
0629             the program without shell intervention (as with os.spawnv()).  If 'cmd'
0630             is a string it will be passed to the shell (as with os.system()). If
0631             'bufsize' is specified, it sets the buffer size for the I/O pipes.  The
0632             file objects (child_stdin, child_stdout, child_stderr) are returned."""
0633             import popen2
0634             stdout, stdin, stderr = popen2.popen3(cmd, bufsize)
0635             return stdin, stdout, stderr
0636         __all__.append("popen3")
0637 
0638     if not _exists("popen4"):
0639         def popen4(cmd, mode="t", bufsize=-1):
0640             """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'
0641             may be a sequence, in which case arguments will be passed directly to
0642             the program without shell intervention (as with os.spawnv()).  If 'cmd'
0643             is a string it will be passed to the shell (as with os.system()). If
0644             'bufsize' is specified, it sets the buffer size for the I/O pipes.  The
0645             file objects (child_stdin, child_stdout_stderr) are returned."""
0646             import popen2
0647             stdout, stdin = popen2.popen4(cmd, bufsize)
0648             return stdin, stdout
0649         __all__.append("popen4")
0650 
0651 import copy_reg as _copy_reg
0652 
0653 def _make_stat_result(tup, dict):
0654     return stat_result(tup, dict)
0655 
0656 def _pickle_stat_result(sr):
0657     (type, args) = sr.__reduce__()
0658     return (_make_stat_result, args)
0659 
0660 try:
0661     _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)
0662 except NameError: # stat_result may not exist
0663     pass
0664 
0665 def _make_statvfs_result(tup, dict):
0666     return statvfs_result(tup, dict)
0667 
0668 def _pickle_statvfs_result(sr):
0669     (type, args) = sr.__reduce__()
0670     return (_make_statvfs_result, args)
0671 
0672 try:
0673     _copy_reg.pickle(statvfs_result, _pickle_statvfs_result,
0674                      _make_statvfs_result)
0675 except NameError: # statvfs_result may not exist
0676     pass
0677 
0678 if not _exists("urandom"):
0679     _urandomfd = None
0680     def urandom(n):
0681         """urandom(n) -> str
0682 
0683         Return a string of n random bytes suitable for cryptographic use.
0684 
0685         """
0686         global _urandomfd
0687         if _urandomfd is None:
0688             try:
0689                 _urandomfd = open("/dev/urandom", O_RDONLY)
0690             except:
0691                 _urandomfd = NotImplementedError
0692         if _urandomfd is NotImplementedError:
0693             raise NotImplementedError("/dev/urandom (or equivalent) not found")
0694         bytes = ""
0695         while len(bytes) < n:
0696             bytes += read(_urandomfd, n - len(bytes))
0697         return bytes
0698 

Generated by PyXR 0.9.4
SourceForge.net Logo