--- /dev/null
+r"""OS routines for Mac, NT, or Posix depending on what system we're on.\r
+\r
+This exports:\r
+ - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.\r
+ - os.path is one of the modules posixpath, or ntpath\r
+ - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'\r
+ - os.curdir is a string representing the current directory ('.' or ':')\r
+ - os.pardir is a string representing the parent directory ('..' or '::')\r
+ - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')\r
+ - os.extsep is the extension separator ('.' or '/')\r
+ - os.altsep is the alternate pathname separator (None or '/')\r
+ - os.pathsep is the component separator used in $PATH etc\r
+ - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')\r
+ - os.defpath is the default search path for executables\r
+ - os.devnull is the file path of the null device ('/dev/null', etc.)\r
+\r
+Programs that import and use 'os' stand a better chance of being\r
+portable between different platforms. Of course, they must then\r
+only use functions that are defined by all platforms (e.g., unlink\r
+and opendir), and leave all pathname manipulation to os.path\r
+(e.g., split and join).\r
+"""\r
+\r
+#'\r
+\r
+import sys, errno\r
+\r
+_names = sys.builtin_module_names\r
+\r
+# Note: more names are added to __all__ later.\r
+__all__ = ["altsep", "curdir", "pardir", "sep", "extsep", "pathsep", "linesep",\r
+ "defpath", "name", "path", "devnull",\r
+ "SEEK_SET", "SEEK_CUR", "SEEK_END"]\r
+\r
+def _get_exports_list(module):\r
+ try:\r
+ return list(module.__all__)\r
+ except AttributeError:\r
+ return [n for n in dir(module) if n[0] != '_']\r
+\r
+if 'posix' in _names:\r
+ name = 'posix'\r
+ linesep = '\n'\r
+ from posix import *\r
+ try:\r
+ from posix import _exit\r
+ except ImportError:\r
+ pass\r
+ import posixpath as path\r
+\r
+ import posix\r
+ __all__.extend(_get_exports_list(posix))\r
+ del posix\r
+\r
+elif 'nt' in _names:\r
+ name = 'nt'\r
+ linesep = '\r\n'\r
+ from nt import *\r
+ try:\r
+ from nt import _exit\r
+ except ImportError:\r
+ pass\r
+ import ntpath as path\r
+\r
+ import nt\r
+ __all__.extend(_get_exports_list(nt))\r
+ del nt\r
+\r
+elif 'os2' in _names:\r
+ name = 'os2'\r
+ linesep = '\r\n'\r
+ from os2 import *\r
+ try:\r
+ from os2 import _exit\r
+ except ImportError:\r
+ pass\r
+ if sys.version.find('EMX GCC') == -1:\r
+ import ntpath as path\r
+ else:\r
+ import os2emxpath as path\r
+ from _emx_link import link\r
+\r
+ import os2\r
+ __all__.extend(_get_exports_list(os2))\r
+ del os2\r
+\r
+elif 'ce' in _names:\r
+ name = 'ce'\r
+ linesep = '\r\n'\r
+ from ce import *\r
+ try:\r
+ from ce import _exit\r
+ except ImportError:\r
+ pass\r
+ # We can use the standard Windows path.\r
+ import ntpath as path\r
+\r
+ import ce\r
+ __all__.extend(_get_exports_list(ce))\r
+ del ce\r
+\r
+elif 'riscos' in _names:\r
+ name = 'riscos'\r
+ linesep = '\n'\r
+ from riscos import *\r
+ try:\r
+ from riscos import _exit\r
+ except ImportError:\r
+ pass\r
+ import riscospath as path\r
+\r
+ import riscos\r
+ __all__.extend(_get_exports_list(riscos))\r
+ del riscos\r
+\r
+else:\r
+ raise ImportError, 'no os specific module found'\r
+\r
+sys.modules['os.path'] = path\r
+from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,\r
+ devnull)\r
+\r
+del _names\r
+\r
+# Python uses fixed values for the SEEK_ constants; they are mapped\r
+# to native constants if necessary in posixmodule.c\r
+SEEK_SET = 0\r
+SEEK_CUR = 1\r
+SEEK_END = 2\r
+\r
+#'\r
+\r
+# Super directory utilities.\r
+# (Inspired by Eric Raymond; the doc strings are mostly his)\r
+\r
+def makedirs(name, mode=0777):\r
+ """makedirs(path [, mode=0777])\r
+\r
+ Super-mkdir; create a leaf directory and all intermediate ones.\r
+ Works like mkdir, except that any intermediate path segment (not\r
+ just the rightmost) will be created if it does not exist. This is\r
+ recursive.\r
+\r
+ """\r
+ head, tail = path.split(name)\r
+ if not tail:\r
+ head, tail = path.split(head)\r
+ if head and tail and not path.exists(head):\r
+ try:\r
+ makedirs(head, mode)\r
+ except OSError, e:\r
+ # be happy if someone already created the path\r
+ if e.errno != errno.EEXIST:\r
+ raise\r
+ if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists\r
+ return\r
+ mkdir(name, mode)\r
+\r
+def removedirs(name):\r
+ """removedirs(path)\r
+\r
+ Super-rmdir; remove a leaf directory and all empty intermediate\r
+ ones. Works like rmdir except that, if the leaf directory is\r
+ successfully removed, directories corresponding to rightmost path\r
+ segments will be pruned away until either the whole path is\r
+ consumed or an error occurs. Errors during this latter phase are\r
+ ignored -- they generally mean that a directory was not empty.\r
+\r
+ """\r
+ rmdir(name)\r
+ head, tail = path.split(name)\r
+ if not tail:\r
+ head, tail = path.split(head)\r
+ while head and tail:\r
+ try:\r
+ rmdir(head)\r
+ except error:\r
+ break\r
+ head, tail = path.split(head)\r
+\r
+def renames(old, new):\r
+ """renames(old, new)\r
+\r
+ Super-rename; create directories as necessary and delete any left\r
+ empty. Works like rename, except creation of any intermediate\r
+ directories needed to make the new pathname good is attempted\r
+ first. After the rename, directories corresponding to rightmost\r
+ path segments of the old name will be pruned way until either the\r
+ whole path is consumed or a nonempty directory is found.\r
+\r
+ Note: this function can fail with the new directory structure made\r
+ if you lack permissions needed to unlink the leaf directory or\r
+ file.\r
+\r
+ """\r
+ head, tail = path.split(new)\r
+ if head and tail and not path.exists(head):\r
+ makedirs(head)\r
+ rename(old, new)\r
+ head, tail = path.split(old)\r
+ if head and tail:\r
+ try:\r
+ removedirs(head)\r
+ except error:\r
+ pass\r
+\r
+__all__.extend(["makedirs", "removedirs", "renames"])\r
+\r
+def walk(top, topdown=True, onerror=None, followlinks=False):\r
+ """Directory tree generator.\r
+\r
+ For each directory in the directory tree rooted at top (including top\r
+ itself, but excluding '.' and '..'), yields a 3-tuple\r
+\r
+ dirpath, dirnames, filenames\r
+\r
+ dirpath is a string, the path to the directory. dirnames is a list of\r
+ the names of the subdirectories in dirpath (excluding '.' and '..').\r
+ filenames is a list of the names of the non-directory files in dirpath.\r
+ Note that the names in the lists are just names, with no path components.\r
+ To get a full path (which begins with top) to a file or directory in\r
+ dirpath, do os.path.join(dirpath, name).\r
+\r
+ If optional arg 'topdown' is true or not specified, the triple for a\r
+ directory is generated before the triples for any of its subdirectories\r
+ (directories are generated top down). If topdown is false, the triple\r
+ for a directory is generated after the triples for all of its\r
+ subdirectories (directories are generated bottom up).\r
+\r
+ When topdown is true, the caller can modify the dirnames list in-place\r
+ (e.g., via del or slice assignment), and walk will only recurse into the\r
+ subdirectories whose names remain in dirnames; this can be used to prune\r
+ the search, or to impose a specific order of visiting. Modifying\r
+ dirnames when topdown is false is ineffective, since the directories in\r
+ dirnames have already been generated by the time dirnames itself is\r
+ generated.\r
+\r
+ By default errors from the os.listdir() call are ignored. If\r
+ optional arg 'onerror' is specified, it should be a function; it\r
+ will be called with one argument, an os.error instance. It can\r
+ report the error to continue with the walk, or raise the exception\r
+ to abort the walk. Note that the filename is available as the\r
+ filename attribute of the exception object.\r
+\r
+ By default, os.walk does not follow symbolic links to subdirectories on\r
+ systems that support them. In order to get this functionality, set the\r
+ optional argument 'followlinks' to true.\r
+\r
+ Caution: if you pass a relative pathname for top, don't change the\r
+ current working directory between resumptions of walk. walk never\r
+ changes the current directory, and assumes that the client doesn't\r
+ either.\r
+\r
+ Example:\r
+\r
+ import os\r
+ from os.path import join, getsize\r
+ for root, dirs, files in os.walk('python/Lib/email'):\r
+ print root, "consumes",\r
+ print sum([getsize(join(root, name)) for name in files]),\r
+ print "bytes in", len(files), "non-directory files"\r
+ if 'CVS' in dirs:\r
+ dirs.remove('CVS') # don't visit CVS directories\r
+ """\r
+\r
+ islink, join, isdir = path.islink, path.join, path.isdir\r
+\r
+ # We may not have read permission for top, in which case we can't\r
+ # get a list of the files the directory contains. os.path.walk\r
+ # always suppressed the exception then, rather than blow up for a\r
+ # minor reason when (say) a thousand readable directories are still\r
+ # left to visit. That logic is copied here.\r
+ try:\r
+ # Note that listdir and error are globals in this module due\r
+ # to earlier import-*.\r
+ names = listdir(top)\r
+ except error, err:\r
+ if onerror is not None:\r
+ onerror(err)\r
+ return\r
+\r
+ dirs, nondirs = [], []\r
+ for name in names:\r
+ if isdir(join(top, name)):\r
+ dirs.append(name)\r
+ else:\r
+ nondirs.append(name)\r
+\r
+ if topdown:\r
+ yield top, dirs, nondirs\r
+ for name in dirs:\r
+ new_path = join(top, name)\r
+ if followlinks or not islink(new_path):\r
+ for x in walk(new_path, topdown, onerror, followlinks):\r
+ yield x\r
+ if not topdown:\r
+ yield top, dirs, nondirs\r
+\r
+__all__.append("walk")\r
+\r
+# Make sure os.environ exists, at least\r
+try:\r
+ environ\r
+except NameError:\r
+ environ = {}\r
+\r
+def execl(file, *args):\r
+ """execl(file, *args)\r
+\r
+ Execute the executable file with argument list args, replacing the\r
+ current process. """\r
+ execv(file, args)\r
+\r
+def execle(file, *args):\r
+ """execle(file, *args, env)\r
+\r
+ Execute the executable file with argument list args and\r
+ environment env, replacing the current process. """\r
+ env = args[-1]\r
+ execve(file, args[:-1], env)\r
+\r
+def execlp(file, *args):\r
+ """execlp(file, *args)\r
+\r
+ Execute the executable file (which is searched for along $PATH)\r
+ with argument list args, replacing the current process. """\r
+ execvp(file, args)\r
+\r
+def execlpe(file, *args):\r
+ """execlpe(file, *args, env)\r
+\r
+ Execute the executable file (which is searched for along $PATH)\r
+ with argument list args and environment env, replacing the current\r
+ process. """\r
+ env = args[-1]\r
+ execvpe(file, args[:-1], env)\r
+\r
+def execvp(file, args):\r
+ """execvp(file, args)\r
+\r
+ Execute the executable file (which is searched for along $PATH)\r
+ with argument list args, replacing the current process.\r
+ args may be a list or tuple of strings. """\r
+ _execvpe(file, args)\r
+\r
+def execvpe(file, args, env):\r
+ """execvpe(file, args, env)\r
+\r
+ Execute the executable file (which is searched for along $PATH)\r
+ with argument list args and environment env , replacing the\r
+ current process.\r
+ args may be a list or tuple of strings. """\r
+ _execvpe(file, args, env)\r
+\r
+__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])\r
+\r
+def _execvpe(file, args, env=None):\r
+ if env is not None:\r
+ func = execve\r
+ argrest = (args, env)\r
+ else:\r
+ func = execv\r
+ argrest = (args,)\r
+ env = environ\r
+\r
+ head, tail = path.split(file)\r
+ if head:\r
+ func(file, *argrest)\r
+ return\r
+ if 'PATH' in env:\r
+ envpath = env['PATH']\r
+ else:\r
+ envpath = defpath\r
+ PATH = envpath.split(pathsep)\r
+ saved_exc = None\r
+ saved_tb = None\r
+ for dir in PATH:\r
+ fullname = path.join(dir, file)\r
+ try:\r
+ func(fullname, *argrest)\r
+ except error, e:\r
+ tb = sys.exc_info()[2]\r
+ if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR\r
+ and saved_exc is None):\r
+ saved_exc = e\r
+ saved_tb = tb\r
+ if saved_exc:\r
+ raise error, saved_exc, saved_tb\r
+ raise error, e, tb\r
+\r
+# Change environ to automatically call putenv() if it exists\r
+try:\r
+ # This will fail if there's no putenv\r
+ putenv\r
+except NameError:\r
+ pass\r
+else:\r
+ import UserDict\r
+\r
+ # Fake unsetenv() for Windows\r
+ # not sure about os2 here but\r
+ # I'm guessing they are the same.\r
+\r
+ if name in ('os2', 'nt'):\r
+ def unsetenv(key):\r
+ putenv(key, "")\r
+\r
+ if name == "riscos":\r
+ # On RISC OS, all env access goes through getenv and putenv\r
+ from riscosenviron import _Environ\r
+ elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE\r
+ # But we store them as upper case\r
+ class _Environ(UserDict.IterableUserDict):\r
+ def __init__(self, environ):\r
+ UserDict.UserDict.__init__(self)\r
+ data = self.data\r
+ for k, v in environ.items():\r
+ data[k.upper()] = v\r
+ def __setitem__(self, key, item):\r
+ putenv(key, item)\r
+ self.data[key.upper()] = item\r
+ def __getitem__(self, key):\r
+ return self.data[key.upper()]\r
+ try:\r
+ unsetenv\r
+ except NameError:\r
+ def __delitem__(self, key):\r
+ del self.data[key.upper()]\r
+ else:\r
+ def __delitem__(self, key):\r
+ unsetenv(key)\r
+ del self.data[key.upper()]\r
+ def clear(self):\r
+ for key in self.data.keys():\r
+ unsetenv(key)\r
+ del self.data[key]\r
+ def pop(self, key, *args):\r
+ unsetenv(key)\r
+ return self.data.pop(key.upper(), *args)\r
+ def has_key(self, key):\r
+ return key.upper() in self.data\r
+ def __contains__(self, key):\r
+ return key.upper() in self.data\r
+ def get(self, key, failobj=None):\r
+ return self.data.get(key.upper(), failobj)\r
+ def update(self, dict=None, **kwargs):\r
+ if dict:\r
+ try:\r
+ keys = dict.keys()\r
+ except AttributeError:\r
+ # List of (key, value)\r
+ for k, v in dict:\r
+ self[k] = v\r
+ else:\r
+ # got keys\r
+ # cannot use items(), since mappings\r
+ # may not have them.\r
+ for k in keys:\r
+ self[k] = dict[k]\r
+ if kwargs:\r
+ self.update(kwargs)\r
+ def copy(self):\r
+ return dict(self)\r
+\r
+ else: # Where Env Var Names Can Be Mixed Case\r
+ class _Environ(UserDict.IterableUserDict):\r
+ def __init__(self, environ):\r
+ UserDict.UserDict.__init__(self)\r
+ self.data = environ\r
+ def __setitem__(self, key, item):\r
+ putenv(key, item)\r
+ self.data[key] = item\r
+ def update(self, dict=None, **kwargs):\r
+ if dict:\r
+ try:\r
+ keys = dict.keys()\r
+ except AttributeError:\r
+ # List of (key, value)\r
+ for k, v in dict:\r
+ self[k] = v\r
+ else:\r
+ # got keys\r
+ # cannot use items(), since mappings\r
+ # may not have them.\r
+ for k in keys:\r
+ self[k] = dict[k]\r
+ if kwargs:\r
+ self.update(kwargs)\r
+ try:\r
+ unsetenv\r
+ except NameError:\r
+ pass\r
+ else:\r
+ def __delitem__(self, key):\r
+ unsetenv(key)\r
+ del self.data[key]\r
+ def clear(self):\r
+ for key in self.data.keys():\r
+ unsetenv(key)\r
+ del self.data[key]\r
+ def pop(self, key, *args):\r
+ unsetenv(key)\r
+ return self.data.pop(key, *args)\r
+ def copy(self):\r
+ return dict(self)\r
+\r
+\r
+ environ = _Environ(environ)\r
+\r
+def getenv(key, default=None):\r
+ """Get an environment variable, return None if it doesn't exist.\r
+ The optional second argument can specify an alternate default."""\r
+ return environ.get(key, default)\r
+__all__.append("getenv")\r
+\r
+def _exists(name):\r
+ return name in globals()\r
+\r
+# Supply spawn*() (probably only for Unix)\r
+if _exists("fork") and not _exists("spawnv") and _exists("execv"):\r
+\r
+ P_WAIT = 0\r
+ P_NOWAIT = P_NOWAITO = 1\r
+\r
+ # XXX Should we support P_DETACH? I suppose it could fork()**2\r
+ # and close the std I/O streams. Also, P_OVERLAY is the same\r
+ # as execv*()?\r
+\r
+ def _spawnvef(mode, file, args, env, func):\r
+ # Internal helper; func is the exec*() function to use\r
+ pid = fork()\r
+ if not pid:\r
+ # Child\r
+ try:\r
+ if env is None:\r
+ func(file, args)\r
+ else:\r
+ func(file, args, env)\r
+ except:\r
+ _exit(127)\r
+ else:\r
+ # Parent\r
+ if mode == P_NOWAIT:\r
+ return pid # Caller is responsible for waiting!\r
+ while 1:\r
+ wpid, sts = waitpid(pid, 0)\r
+ if WIFSTOPPED(sts):\r
+ continue\r
+ elif WIFSIGNALED(sts):\r
+ return -WTERMSIG(sts)\r
+ elif WIFEXITED(sts):\r
+ return WEXITSTATUS(sts)\r
+ else:\r
+ raise error, "Not stopped, signaled or exited???"\r
+\r
+ def spawnv(mode, file, args):\r
+ """spawnv(mode, file, args) -> integer\r
+\r
+Execute file with arguments from args in a subprocess.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+ return _spawnvef(mode, file, args, None, execv)\r
+\r
+ def spawnve(mode, file, args, env):\r
+ """spawnve(mode, file, args, env) -> integer\r
+\r
+Execute file with arguments from args in a subprocess with the\r
+specified environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+ return _spawnvef(mode, file, args, env, execve)\r
+\r
+ # Note: spawnvp[e] is't currently supported on Windows\r
+\r
+ def spawnvp(mode, file, args):\r
+ """spawnvp(mode, file, args) -> integer\r
+\r
+Execute file (which is looked for along $PATH) with arguments from\r
+args in a subprocess.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+ return _spawnvef(mode, file, args, None, execvp)\r
+\r
+ def spawnvpe(mode, file, args, env):\r
+ """spawnvpe(mode, file, args, env) -> integer\r
+\r
+Execute file (which is looked for along $PATH) with arguments from\r
+args in a subprocess with the supplied environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+ return _spawnvef(mode, file, args, env, execvpe)\r
+\r
+if _exists("spawnv"):\r
+ # These aren't supplied by the basic Windows code\r
+ # but can be easily implemented in Python\r
+\r
+ def spawnl(mode, file, *args):\r
+ """spawnl(mode, file, *args) -> integer\r
+\r
+Execute file with arguments from args in a subprocess.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+ return spawnv(mode, file, args)\r
+\r
+ def spawnle(mode, file, *args):\r
+ """spawnle(mode, file, *args, env) -> integer\r
+\r
+Execute file with arguments from args in a subprocess with the\r
+supplied environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+ env = args[-1]\r
+ return spawnve(mode, file, args[:-1], env)\r
+\r
+\r
+ __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])\r
+\r
+\r
+if _exists("spawnvp"):\r
+ # At the moment, Windows doesn't implement spawnvp[e],\r
+ # so it won't have spawnlp[e] either.\r
+ def spawnlp(mode, file, *args):\r
+ """spawnlp(mode, file, *args) -> integer\r
+\r
+Execute file (which is looked for along $PATH) with arguments from\r
+args in a subprocess with the supplied environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+ return spawnvp(mode, file, args)\r
+\r
+ def spawnlpe(mode, file, *args):\r
+ """spawnlpe(mode, file, *args, env) -> integer\r
+\r
+Execute file (which is looked for along $PATH) with arguments from\r
+args in a subprocess with the supplied environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+ env = args[-1]\r
+ return spawnvpe(mode, file, args[:-1], env)\r
+\r
+\r
+ __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])\r
+\r
+\r
+# Supply popen2 etc. (for Unix)\r
+if _exists("fork"):\r
+ if not _exists("popen2"):\r
+ def popen2(cmd, mode="t", bufsize=-1):\r
+ """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'\r
+ may be a sequence, in which case arguments will be passed directly to\r
+ the program without shell intervention (as with os.spawnv()). If 'cmd'\r
+ is a string it will be passed to the shell (as with os.system()). If\r
+ 'bufsize' is specified, it sets the buffer size for the I/O pipes. The\r
+ file objects (child_stdin, child_stdout) are returned."""\r
+ import warnings\r
+ msg = "os.popen2 is deprecated. Use the subprocess module."\r
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)\r
+\r
+ import subprocess\r
+ PIPE = subprocess.PIPE\r
+ p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),\r
+ bufsize=bufsize, stdin=PIPE, stdout=PIPE,\r
+ close_fds=True)\r
+ return p.stdin, p.stdout\r
+ __all__.append("popen2")\r
+\r
+ if not _exists("popen3"):\r
+ def popen3(cmd, mode="t", bufsize=-1):\r
+ """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'\r
+ may be a sequence, in which case arguments will be passed directly to\r
+ the program without shell intervention (as with os.spawnv()). If 'cmd'\r
+ is a string it will be passed to the shell (as with os.system()). If\r
+ 'bufsize' is specified, it sets the buffer size for the I/O pipes. The\r
+ file objects (child_stdin, child_stdout, child_stderr) are returned."""\r
+ import warnings\r
+ msg = "os.popen3 is deprecated. Use the subprocess module."\r
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)\r
+\r
+ import subprocess\r
+ PIPE = subprocess.PIPE\r
+ p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),\r
+ bufsize=bufsize, stdin=PIPE, stdout=PIPE,\r
+ stderr=PIPE, close_fds=True)\r
+ return p.stdin, p.stdout, p.stderr\r
+ __all__.append("popen3")\r
+\r
+ if not _exists("popen4"):\r
+ def popen4(cmd, mode="t", bufsize=-1):\r
+ """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'\r
+ may be a sequence, in which case arguments will be passed directly to\r
+ the program without shell intervention (as with os.spawnv()). If 'cmd'\r
+ is a string it will be passed to the shell (as with os.system()). If\r
+ 'bufsize' is specified, it sets the buffer size for the I/O pipes. The\r
+ file objects (child_stdin, child_stdout_stderr) are returned."""\r
+ import warnings\r
+ msg = "os.popen4 is deprecated. Use the subprocess module."\r
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)\r
+\r
+ import subprocess\r
+ PIPE = subprocess.PIPE\r
+ p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),\r
+ bufsize=bufsize, stdin=PIPE, stdout=PIPE,\r
+ stderr=subprocess.STDOUT, close_fds=True)\r
+ return p.stdin, p.stdout\r
+ __all__.append("popen4")\r
+\r
+import copy_reg as _copy_reg\r
+\r
+def _make_stat_result(tup, dict):\r
+ return stat_result(tup, dict)\r
+\r
+def _pickle_stat_result(sr):\r
+ (type, args) = sr.__reduce__()\r
+ return (_make_stat_result, args)\r
+\r
+try:\r
+ _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)\r
+except NameError: # stat_result may not exist\r
+ pass\r
+\r
+def _make_statvfs_result(tup, dict):\r
+ return statvfs_result(tup, dict)\r
+\r
+def _pickle_statvfs_result(sr):\r
+ (type, args) = sr.__reduce__()\r
+ return (_make_statvfs_result, args)\r
+\r
+try:\r
+ _copy_reg.pickle(statvfs_result, _pickle_statvfs_result,\r
+ _make_statvfs_result)\r
+except NameError: # statvfs_result may not exist\r
+ pass\r
+\r
+if not _exists("urandom"):\r
+ def urandom(n):\r
+ """urandom(n) -> str\r
+\r
+ Return a string of n random bytes suitable for cryptographic use.\r
+\r
+ """\r
+ try:\r
+ _urandomfd = open("/dev/urandom", O_RDONLY)\r
+ except (OSError, IOError):\r
+ raise NotImplementedError("/dev/urandom (or equivalent) not found")\r
+ try:\r
+ bs = b""\r
+ while n > len(bs):\r
+ bs += read(_urandomfd, n - len(bs))\r
+ finally:\r
+ close(_urandomfd)\r
+ return bs\r