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