os.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. r"""OS routines for 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 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 the
  193. search, or to impose a specific order of visiting. Modifying dirnames when
  194. topdown is false is ineffective, since the directories in dirnames have
  195. already been generated by the time dirnames itself is generated. No matter
  196. the value of topdown, the list of subdirectories is retrieved before the
  197. tuples for the directory and its subdirectories are generated.
  198. By default errors from the os.listdir() call are ignored. If
  199. optional arg 'onerror' is specified, it should be a function; it
  200. will be called with one argument, an os.error instance. It can
  201. report the error to continue with the walk, or raise the exception
  202. to abort the walk. Note that the filename is available as the
  203. filename attribute of the exception object.
  204. By default, os.walk does not follow symbolic links to subdirectories on
  205. systems that support them. In order to get this functionality, set the
  206. optional argument 'followlinks' to true.
  207. Caution: if you pass a relative pathname for top, don't change the
  208. current working directory between resumptions of walk. walk never
  209. changes the current directory, and assumes that the client doesn't
  210. either.
  211. Example:
  212. import os
  213. from os.path import join, getsize
  214. for root, dirs, files in os.walk('python/Lib/email'):
  215. print root, "consumes",
  216. print sum([getsize(join(root, name)) for name in files]),
  217. print "bytes in", len(files), "non-directory files"
  218. if 'CVS' in dirs:
  219. dirs.remove('CVS') # don't visit CVS directories
  220. """
  221. islink, join, isdir = path.islink, path.join, path.isdir
  222. # We may not have read permission for top, in which case we can't
  223. # get a list of the files the directory contains. os.path.walk
  224. # always suppressed the exception then, rather than blow up for a
  225. # minor reason when (say) a thousand readable directories are still
  226. # left to visit. That logic is copied here.
  227. try:
  228. # Note that listdir and error are globals in this module due
  229. # to earlier import-*.
  230. names = listdir(top)
  231. except error, err:
  232. if onerror is not None:
  233. onerror(err)
  234. return
  235. dirs, nondirs = [], []
  236. for name in names:
  237. if isdir(join(top, name)):
  238. dirs.append(name)
  239. else:
  240. nondirs.append(name)
  241. if topdown:
  242. yield top, dirs, nondirs
  243. for name in dirs:
  244. new_path = join(top, name)
  245. if followlinks or not islink(new_path):
  246. for x in walk(new_path, topdown, onerror, followlinks):
  247. yield x
  248. if not topdown:
  249. yield top, dirs, nondirs
  250. __all__.append("walk")
  251. # Make sure os.environ exists, at least
  252. try:
  253. environ
  254. except NameError:
  255. environ = {}
  256. def execl(file, *args):
  257. """execl(file, *args)
  258. Execute the executable file with argument list args, replacing the
  259. current process. """
  260. execv(file, args)
  261. def execle(file, *args):
  262. """execle(file, *args, env)
  263. Execute the executable file with argument list args and
  264. environment env, replacing the current process. """
  265. env = args[-1]
  266. execve(file, args[:-1], env)
  267. def execlp(file, *args):
  268. """execlp(file, *args)
  269. Execute the executable file (which is searched for along $PATH)
  270. with argument list args, replacing the current process. """
  271. execvp(file, args)
  272. def execlpe(file, *args):
  273. """execlpe(file, *args, env)
  274. Execute the executable file (which is searched for along $PATH)
  275. with argument list args and environment env, replacing the current
  276. process. """
  277. env = args[-1]
  278. execvpe(file, args[:-1], env)
  279. def execvp(file, args):
  280. """execvp(file, args)
  281. Execute the executable file (which is searched for along $PATH)
  282. with argument list args, replacing the current process.
  283. args may be a list or tuple of strings. """
  284. _execvpe(file, args)
  285. def execvpe(file, args, env):
  286. """execvpe(file, args, env)
  287. Execute the executable file (which is searched for along $PATH)
  288. with argument list args and environment env , replacing the
  289. current process.
  290. args may be a list or tuple of strings. """
  291. _execvpe(file, args, env)
  292. __all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
  293. def _execvpe(file, args, env=None):
  294. if env is not None:
  295. func = execve
  296. argrest = (args, env)
  297. else:
  298. func = execv
  299. argrest = (args,)
  300. env = environ
  301. head, tail = path.split(file)
  302. if head:
  303. func(file, *argrest)
  304. return
  305. if 'PATH' in env:
  306. envpath = env['PATH']
  307. else:
  308. envpath = defpath
  309. PATH = envpath.split(pathsep)
  310. saved_exc = None
  311. saved_tb = None
  312. for dir in PATH:
  313. fullname = path.join(dir, file)
  314. try:
  315. func(fullname, *argrest)
  316. except error, e:
  317. tb = sys.exc_info()[2]
  318. if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR
  319. and saved_exc is None):
  320. saved_exc = e
  321. saved_tb = tb
  322. if saved_exc:
  323. raise error, saved_exc, saved_tb
  324. raise error, e, tb
  325. # Change environ to automatically call putenv() if it exists
  326. try:
  327. # This will fail if there's no putenv
  328. putenv
  329. except NameError:
  330. pass
  331. else:
  332. import UserDict
  333. # Fake unsetenv() for Windows
  334. # not sure about os2 here but
  335. # I'm guessing they are the same.
  336. if name in ('os2', 'nt'):
  337. def unsetenv(key):
  338. putenv(key, "")
  339. if name == "riscos":
  340. # On RISC OS, all env access goes through getenv and putenv
  341. from riscosenviron import _Environ
  342. elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE
  343. # But we store them as upper case
  344. class _Environ(UserDict.IterableUserDict):
  345. def __init__(self, environ):
  346. UserDict.UserDict.__init__(self)
  347. data = self.data
  348. for k, v in environ.items():
  349. data[k.upper()] = v
  350. def __setitem__(self, key, item):
  351. putenv(key, item)
  352. self.data[key.upper()] = item
  353. def __getitem__(self, key):
  354. return self.data[key.upper()]
  355. try:
  356. unsetenv
  357. except NameError:
  358. def __delitem__(self, key):
  359. del self.data[key.upper()]
  360. else:
  361. def __delitem__(self, key):
  362. unsetenv(key)
  363. del self.data[key.upper()]
  364. def clear(self):
  365. for key in self.data.keys():
  366. unsetenv(key)
  367. del self.data[key]
  368. def pop(self, key, *args):
  369. unsetenv(key)
  370. return self.data.pop(key.upper(), *args)
  371. def has_key(self, key):
  372. return key.upper() in self.data
  373. def __contains__(self, key):
  374. return key.upper() in self.data
  375. def get(self, key, failobj=None):
  376. return self.data.get(key.upper(), failobj)
  377. def update(self, dict=None, **kwargs):
  378. if dict:
  379. try:
  380. keys = dict.keys()
  381. except AttributeError:
  382. # List of (key, value)
  383. for k, v in dict:
  384. self[k] = v
  385. else:
  386. # got keys
  387. # cannot use items(), since mappings
  388. # may not have them.
  389. for k in keys:
  390. self[k] = dict[k]
  391. if kwargs:
  392. self.update(kwargs)
  393. def copy(self):
  394. return dict(self)
  395. else: # Where Env Var Names Can Be Mixed Case
  396. class _Environ(UserDict.IterableUserDict):
  397. def __init__(self, environ):
  398. UserDict.UserDict.__init__(self)
  399. self.data = environ
  400. def __setitem__(self, key, item):
  401. putenv(key, item)
  402. self.data[key] = item
  403. def update(self, dict=None, **kwargs):
  404. if dict:
  405. try:
  406. keys = dict.keys()
  407. except AttributeError:
  408. # List of (key, value)
  409. for k, v in dict:
  410. self[k] = v
  411. else:
  412. # got keys
  413. # cannot use items(), since mappings
  414. # may not have them.
  415. for k in keys:
  416. self[k] = dict[k]
  417. if kwargs:
  418. self.update(kwargs)
  419. try:
  420. unsetenv
  421. except NameError:
  422. pass
  423. else:
  424. def __delitem__(self, key):
  425. unsetenv(key)
  426. del self.data[key]
  427. def clear(self):
  428. for key in self.data.keys():
  429. unsetenv(key)
  430. del self.data[key]
  431. def pop(self, key, *args):
  432. unsetenv(key)
  433. return self.data.pop(key, *args)
  434. def copy(self):
  435. return dict(self)
  436. environ = _Environ(environ)
  437. def getenv(key, default=None):
  438. """Get an environment variable, return None if it doesn't exist.
  439. The optional second argument can specify an alternate default."""
  440. return environ.get(key, default)
  441. __all__.append("getenv")
  442. def _exists(name):
  443. return name in globals()
  444. # Supply spawn*() (probably only for Unix)
  445. if _exists("fork") and not _exists("spawnv") and _exists("execv"):
  446. P_WAIT = 0
  447. P_NOWAIT = P_NOWAITO = 1
  448. # XXX Should we support P_DETACH? I suppose it could fork()**2
  449. # and close the std I/O streams. Also, P_OVERLAY is the same
  450. # as execv*()?
  451. def _spawnvef(mode, file, args, env, func):
  452. # Internal helper; func is the exec*() function to use
  453. pid = fork()
  454. if not pid:
  455. # Child
  456. try:
  457. if env is None:
  458. func(file, args)
  459. else:
  460. func(file, args, env)
  461. except:
  462. _exit(127)
  463. else:
  464. # Parent
  465. if mode == P_NOWAIT:
  466. return pid # Caller is responsible for waiting!
  467. while 1:
  468. wpid, sts = waitpid(pid, 0)
  469. if WIFSTOPPED(sts):
  470. continue
  471. elif WIFSIGNALED(sts):
  472. return -WTERMSIG(sts)
  473. elif WIFEXITED(sts):
  474. return WEXITSTATUS(sts)
  475. else:
  476. raise error, "Not stopped, signaled or exited???"
  477. def spawnv(mode, file, args):
  478. """spawnv(mode, file, args) -> integer
  479. Execute file with arguments from args in a subprocess.
  480. If mode == P_NOWAIT return the pid of the process.
  481. If mode == P_WAIT return the process's exit code if it exits normally;
  482. otherwise return -SIG, where SIG is the signal that killed it. """
  483. return _spawnvef(mode, file, args, None, execv)
  484. def spawnve(mode, file, args, env):
  485. """spawnve(mode, file, args, env) -> integer
  486. Execute file with arguments from args in a subprocess with the
  487. specified environment.
  488. If mode == P_NOWAIT return the pid of the process.
  489. If mode == P_WAIT return the process's exit code if it exits normally;
  490. otherwise return -SIG, where SIG is the signal that killed it. """
  491. return _spawnvef(mode, file, args, env, execve)
  492. # Note: spawnvp[e] is't currently supported on Windows
  493. def spawnvp(mode, file, args):
  494. """spawnvp(mode, file, args) -> integer
  495. Execute file (which is looked for along $PATH) with arguments from
  496. args in a subprocess.
  497. If mode == P_NOWAIT return the pid of the process.
  498. If mode == P_WAIT return the process's exit code if it exits normally;
  499. otherwise return -SIG, where SIG is the signal that killed it. """
  500. return _spawnvef(mode, file, args, None, execvp)
  501. def spawnvpe(mode, file, args, env):
  502. """spawnvpe(mode, file, args, env) -> integer
  503. Execute file (which is looked for along $PATH) with arguments from
  504. args in a subprocess with the supplied environment.
  505. If mode == P_NOWAIT return the pid of the process.
  506. If mode == P_WAIT return the process's exit code if it exits normally;
  507. otherwise return -SIG, where SIG is the signal that killed it. """
  508. return _spawnvef(mode, file, args, env, execvpe)
  509. if _exists("spawnv"):
  510. # These aren't supplied by the basic Windows code
  511. # but can be easily implemented in Python
  512. def spawnl(mode, file, *args):
  513. """spawnl(mode, file, *args) -> integer
  514. Execute file with arguments from args in a subprocess.
  515. If mode == P_NOWAIT return the pid of the process.
  516. If mode == P_WAIT return the process's exit code if it exits normally;
  517. otherwise return -SIG, where SIG is the signal that killed it. """
  518. return spawnv(mode, file, args)
  519. def spawnle(mode, file, *args):
  520. """spawnle(mode, file, *args, env) -> integer
  521. Execute file with arguments from args in a subprocess with the
  522. supplied environment.
  523. If mode == P_NOWAIT return the pid of the process.
  524. If mode == P_WAIT return the process's exit code if it exits normally;
  525. otherwise return -SIG, where SIG is the signal that killed it. """
  526. env = args[-1]
  527. return spawnve(mode, file, args[:-1], env)
  528. __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])
  529. if _exists("spawnvp"):
  530. # At the moment, Windows doesn't implement spawnvp[e],
  531. # so it won't have spawnlp[e] either.
  532. def spawnlp(mode, file, *args):
  533. """spawnlp(mode, file, *args) -> integer
  534. Execute file (which is looked for along $PATH) with arguments from
  535. args in a subprocess with the supplied environment.
  536. If mode == P_NOWAIT return the pid of the process.
  537. If mode == P_WAIT return the process's exit code if it exits normally;
  538. otherwise return -SIG, where SIG is the signal that killed it. """
  539. return spawnvp(mode, file, args)
  540. def spawnlpe(mode, file, *args):
  541. """spawnlpe(mode, file, *args, env) -> integer
  542. Execute file (which is looked for along $PATH) with arguments from
  543. args in a subprocess with the supplied environment.
  544. If mode == P_NOWAIT return the pid of the process.
  545. If mode == P_WAIT return the process's exit code if it exits normally;
  546. otherwise return -SIG, where SIG is the signal that killed it. """
  547. env = args[-1]
  548. return spawnvpe(mode, file, args[:-1], env)
  549. __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])
  550. # Supply popen2 etc. (for Unix)
  551. if _exists("fork"):
  552. if not _exists("popen2"):
  553. def popen2(cmd, mode="t", bufsize=-1):
  554. """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
  555. may be a sequence, in which case arguments will be passed directly to
  556. the program without shell intervention (as with os.spawnv()). If 'cmd'
  557. is a string it will be passed to the shell (as with os.system()). If
  558. 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
  559. file objects (child_stdin, child_stdout) are returned."""
  560. import warnings
  561. msg = "os.popen2 is deprecated. Use the subprocess module."
  562. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  563. import subprocess
  564. PIPE = subprocess.PIPE
  565. p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),
  566. bufsize=bufsize, stdin=PIPE, stdout=PIPE,
  567. close_fds=True)
  568. return p.stdin, p.stdout
  569. __all__.append("popen2")
  570. if not _exists("popen3"):
  571. def popen3(cmd, mode="t", bufsize=-1):
  572. """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
  573. may be a sequence, in which case arguments will be passed directly to
  574. the program without shell intervention (as with os.spawnv()). If 'cmd'
  575. is a string it will be passed to the shell (as with os.system()). If
  576. 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
  577. file objects (child_stdin, child_stdout, child_stderr) are returned."""
  578. import warnings
  579. msg = "os.popen3 is deprecated. Use the subprocess module."
  580. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  581. import subprocess
  582. PIPE = subprocess.PIPE
  583. p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),
  584. bufsize=bufsize, stdin=PIPE, stdout=PIPE,
  585. stderr=PIPE, close_fds=True)
  586. return p.stdin, p.stdout, p.stderr
  587. __all__.append("popen3")
  588. if not _exists("popen4"):
  589. def popen4(cmd, mode="t", bufsize=-1):
  590. """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
  591. may be a sequence, in which case arguments will be passed directly to
  592. the program without shell intervention (as with os.spawnv()). If 'cmd'
  593. is a string it will be passed to the shell (as with os.system()). If
  594. 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
  595. file objects (child_stdin, child_stdout_stderr) are returned."""
  596. import warnings
  597. msg = "os.popen4 is deprecated. Use the subprocess module."
  598. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  599. import subprocess
  600. PIPE = subprocess.PIPE
  601. p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),
  602. bufsize=bufsize, stdin=PIPE, stdout=PIPE,
  603. stderr=subprocess.STDOUT, close_fds=True)
  604. return p.stdin, p.stdout
  605. __all__.append("popen4")
  606. import copy_reg as _copy_reg
  607. def _make_stat_result(tup, dict):
  608. return stat_result(tup, dict)
  609. def _pickle_stat_result(sr):
  610. (type, args) = sr.__reduce__()
  611. return (_make_stat_result, args)
  612. try:
  613. _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)
  614. except NameError: # stat_result may not exist
  615. pass
  616. def _make_statvfs_result(tup, dict):
  617. return statvfs_result(tup, dict)
  618. def _pickle_statvfs_result(sr):
  619. (type, args) = sr.__reduce__()
  620. return (_make_statvfs_result, args)
  621. try:
  622. _copy_reg.pickle(statvfs_result, _pickle_statvfs_result,
  623. _make_statvfs_result)
  624. except NameError: # statvfs_result may not exist
  625. pass