PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/os.py

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