popen2.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. """Spawn a command with pipes to its stdin, stdout, and optionally stderr.
  2. The normal os.popen(cmd, mode) call spawns a shell command and provides a
  3. file interface to just the input or output of the process depending on
  4. whether mode is 'r' or 'w'. This module provides the functions popen2(cmd)
  5. and popen3(cmd) which return two or three pipes to the spawned command.
  6. """
  7. import os
  8. import sys
  9. import warnings
  10. warnings.warn("The popen2 module is deprecated. Use the subprocess module.",
  11. DeprecationWarning, stacklevel=2)
  12. __all__ = ["popen2", "popen3", "popen4"]
  13. try:
  14. MAXFD = os.sysconf('SC_OPEN_MAX')
  15. except (AttributeError, ValueError):
  16. MAXFD = 256
  17. _active = []
  18. def _cleanup():
  19. for inst in _active[:]:
  20. if inst.poll(_deadstate=sys.maxint) >= 0:
  21. try:
  22. _active.remove(inst)
  23. except ValueError:
  24. # This can happen if two threads create a new Popen instance.
  25. # It's harmless that it was already removed, so ignore.
  26. pass
  27. class Popen3:
  28. """Class representing a child process. Normally, instances are created
  29. internally by the functions popen2() and popen3()."""
  30. sts = -1 # Child not completed yet
  31. def __init__(self, cmd, capturestderr=False, bufsize=-1):
  32. """The parameter 'cmd' is the shell command to execute in a
  33. sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments
  34. will be passed directly to the program without shell intervention (as
  35. with os.spawnv()). If 'cmd' is a string it will be passed to the shell
  36. (as with os.system()). The 'capturestderr' flag, if true, specifies
  37. that the object should capture standard error output of the child
  38. process. The default is false. If the 'bufsize' parameter is
  39. specified, it specifies the size of the I/O buffers to/from the child
  40. process."""
  41. _cleanup()
  42. self.cmd = cmd
  43. p2cread, p2cwrite = os.pipe()
  44. c2pread, c2pwrite = os.pipe()
  45. if capturestderr:
  46. errout, errin = os.pipe()
  47. self.pid = os.fork()
  48. if self.pid == 0:
  49. # Child
  50. os.dup2(p2cread, 0)
  51. os.dup2(c2pwrite, 1)
  52. if capturestderr:
  53. os.dup2(errin, 2)
  54. self._run_child(cmd)
  55. os.close(p2cread)
  56. self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
  57. os.close(c2pwrite)
  58. self.fromchild = os.fdopen(c2pread, 'r', bufsize)
  59. if capturestderr:
  60. os.close(errin)
  61. self.childerr = os.fdopen(errout, 'r', bufsize)
  62. else:
  63. self.childerr = None
  64. def __del__(self):
  65. # In case the child hasn't been waited on, check if it's done.
  66. self.poll(_deadstate=sys.maxint)
  67. if self.sts < 0:
  68. if _active is not None:
  69. # Child is still running, keep us alive until we can wait on it.
  70. _active.append(self)
  71. def _run_child(self, cmd):
  72. if isinstance(cmd, basestring):
  73. cmd = ['/bin/sh', '-c', cmd]
  74. os.closerange(3, MAXFD)
  75. try:
  76. os.execvp(cmd[0], cmd)
  77. finally:
  78. os._exit(1)
  79. def poll(self, _deadstate=None):
  80. """Return the exit status of the child process if it has finished,
  81. or -1 if it hasn't finished yet."""
  82. if self.sts < 0:
  83. try:
  84. pid, sts = os.waitpid(self.pid, os.WNOHANG)
  85. # pid will be 0 if self.pid hasn't terminated
  86. if pid == self.pid:
  87. self.sts = sts
  88. except os.error:
  89. if _deadstate is not None:
  90. self.sts = _deadstate
  91. return self.sts
  92. def wait(self):
  93. """Wait for and return the exit status of the child process."""
  94. if self.sts < 0:
  95. pid, sts = os.waitpid(self.pid, 0)
  96. # This used to be a test, but it is believed to be
  97. # always true, so I changed it to an assertion - mvl
  98. assert pid == self.pid
  99. self.sts = sts
  100. return self.sts
  101. class Popen4(Popen3):
  102. childerr = None
  103. def __init__(self, cmd, bufsize=-1):
  104. _cleanup()
  105. self.cmd = cmd
  106. p2cread, p2cwrite = os.pipe()
  107. c2pread, c2pwrite = os.pipe()
  108. self.pid = os.fork()
  109. if self.pid == 0:
  110. # Child
  111. os.dup2(p2cread, 0)
  112. os.dup2(c2pwrite, 1)
  113. os.dup2(c2pwrite, 2)
  114. self._run_child(cmd)
  115. os.close(p2cread)
  116. self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
  117. os.close(c2pwrite)
  118. self.fromchild = os.fdopen(c2pread, 'r', bufsize)
  119. if sys.platform[:3] == "win" or sys.platform == "os2emx":
  120. # Some things don't make sense on non-Unix platforms.
  121. del Popen3, Popen4
  122. def popen2(cmd, bufsize=-1, mode='t'):
  123. """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
  124. be a sequence, in which case arguments will be passed directly to the
  125. program without shell intervention (as with os.spawnv()). If 'cmd' is a
  126. string it will be passed to the shell (as with os.system()). If
  127. 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
  128. file objects (child_stdout, child_stdin) are returned."""
  129. w, r = os.popen2(cmd, mode, bufsize)
  130. return r, w
  131. def popen3(cmd, bufsize=-1, mode='t'):
  132. """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
  133. be a sequence, in which case arguments will be passed directly to the
  134. program without shell intervention (as with os.spawnv()). If 'cmd' is a
  135. string it will be passed to the shell (as with os.system()). If
  136. 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
  137. file objects (child_stdout, child_stdin, child_stderr) are returned."""
  138. w, r, e = os.popen3(cmd, mode, bufsize)
  139. return r, w, e
  140. def popen4(cmd, bufsize=-1, mode='t'):
  141. """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
  142. be a sequence, in which case arguments will be passed directly to the
  143. program without shell intervention (as with os.spawnv()). If 'cmd' is a
  144. string it will be passed to the shell (as with os.system()). If
  145. 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
  146. file objects (child_stdout_stderr, child_stdin) are returned."""
  147. w, r = os.popen4(cmd, mode, bufsize)
  148. return r, w
  149. else:
  150. def popen2(cmd, bufsize=-1, mode='t'):
  151. """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
  152. be a sequence, in which case arguments will be passed directly to the
  153. program without shell intervention (as with os.spawnv()). If 'cmd' is a
  154. string it will be passed to the shell (as with os.system()). If
  155. 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
  156. file objects (child_stdout, child_stdin) are returned."""
  157. inst = Popen3(cmd, False, bufsize)
  158. return inst.fromchild, inst.tochild
  159. def popen3(cmd, bufsize=-1, mode='t'):
  160. """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
  161. be a sequence, in which case arguments will be passed directly to the
  162. program without shell intervention (as with os.spawnv()). If 'cmd' is a
  163. string it will be passed to the shell (as with os.system()). If
  164. 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
  165. file objects (child_stdout, child_stdin, child_stderr) are returned."""
  166. inst = Popen3(cmd, True, bufsize)
  167. return inst.fromchild, inst.tochild, inst.childerr
  168. def popen4(cmd, bufsize=-1, mode='t'):
  169. """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
  170. be a sequence, in which case arguments will be passed directly to the
  171. program without shell intervention (as with os.spawnv()). If 'cmd' is a
  172. string it will be passed to the shell (as with os.system()). If
  173. 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
  174. file objects (child_stdout_stderr, child_stdin) are returned."""
  175. inst = Popen4(cmd, bufsize)
  176. return inst.fromchild, inst.tochild
  177. __all__.extend(["Popen3", "Popen4"])