Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 1 | """Spawn a command with pipes to its stdin, stdout, and optionally stderr. |
| 2 | |
| 3 | The normal os.popen(cmd, mode) call spawns a shell command and provides a |
| 4 | file interface to just the input or output of the process depending on |
| 5 | whether mode is 'r' or 'w'. This module provides the functions popen2(cmd) |
| 6 | and popen3(cmd) which return two or three pipes to the spawned command. |
| 7 | """ |
| 8 | |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 9 | import os |
| 10 | import sys |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 11 | |
Skip Montanaro | 57fd45e | 2002-03-12 19:48:03 +0000 | [diff] [blame] | 12 | __all__ = ["popen2", "popen3", "popen4"] |
Skip Montanaro | 352674d | 2001-02-07 23:14:30 +0000 | [diff] [blame] | 13 | |
Martin v. Löwis | f563c8b | 2003-10-06 21:34:33 +0000 | [diff] [blame] | 14 | try: |
| 15 | MAXFD = os.sysconf('SC_OPEN_MAX') |
| 16 | except (AttributeError, ValueError): |
| 17 | MAXFD = 256 |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 18 | |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 19 | _active = [] |
| 20 | |
| 21 | def _cleanup(): |
| 22 | for inst in _active[:]: |
Martin v. Löwis | 478c82d | 2006-03-24 08:14:54 +0000 | [diff] [blame] | 23 | if inst.poll(_deadstate=sys.maxint) >= 0: |
| 24 | try: |
| 25 | _active.remove(inst) |
| 26 | except ValueError: |
| 27 | # This can happen if two threads create a new Popen instance. |
| 28 | # It's harmless that it was already removed, so ignore. |
| 29 | pass |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 30 | |
| 31 | class Popen3: |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 32 | """Class representing a child process. Normally instances are created |
| 33 | by the factory functions popen2() and popen3().""" |
| 34 | |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 35 | sts = -1 # Child not completed yet |
| 36 | |
Fred Drake | b5aa407 | 2003-07-07 21:36:19 +0000 | [diff] [blame] | 37 | def __init__(self, cmd, capturestderr=False, bufsize=-1): |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 38 | """The parameter 'cmd' is the shell command to execute in a |
Johannes Gijsbers | 9fc9789 | 2004-10-11 18:12:20 +0000 | [diff] [blame] | 39 | sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments |
| 40 | will be passed directly to the program without shell intervention (as |
| 41 | with os.spawnv()). If 'cmd' is a string it will be passed to the shell |
| 42 | (as with os.system()). The 'capturestderr' flag, if true, specifies |
| 43 | that the object should capture standard error output of the child |
| 44 | process. The default is false. If the 'bufsize' parameter is |
| 45 | specified, it specifies the size of the I/O buffers to/from the child |
| 46 | process.""" |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 47 | _cleanup() |
Martin v. Löwis | bd8dbab | 2006-03-23 18:18:35 +0000 | [diff] [blame] | 48 | self.cmd = cmd |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 49 | p2cread, p2cwrite = os.pipe() |
| 50 | c2pread, c2pwrite = os.pipe() |
| 51 | if capturestderr: |
| 52 | errout, errin = os.pipe() |
| 53 | self.pid = os.fork() |
| 54 | if self.pid == 0: |
| 55 | # Child |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 56 | os.dup2(p2cread, 0) |
| 57 | os.dup2(c2pwrite, 1) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 58 | if capturestderr: |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 59 | os.dup2(errin, 2) |
| 60 | self._run_child(cmd) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 61 | os.close(p2cread) |
| 62 | self.tochild = os.fdopen(p2cwrite, 'w', bufsize) |
| 63 | os.close(c2pwrite) |
| 64 | self.fromchild = os.fdopen(c2pread, 'r', bufsize) |
| 65 | if capturestderr: |
| 66 | os.close(errin) |
| 67 | self.childerr = os.fdopen(errout, 'r', bufsize) |
| 68 | else: |
| 69 | self.childerr = None |
Martin v. Löwis | 478c82d | 2006-03-24 08:14:54 +0000 | [diff] [blame] | 70 | |
| 71 | def __del__(self): |
| 72 | # In case the child hasn't been waited on, check if it's done. |
| 73 | self.poll(_deadstate=sys.maxint) |
| 74 | if self.sts < 0: |
| 75 | # Child is still running, keep us alive until we can wait on it. |
| 76 | _active.append(self) |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 77 | |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 78 | def _run_child(self, cmd): |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 79 | if isinstance(cmd, basestring): |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 80 | cmd = ['/bin/sh', '-c', cmd] |
| 81 | for i in range(3, MAXFD): |
| 82 | try: |
| 83 | os.close(i) |
Skip Montanaro | 1c90d7a | 2002-03-24 20:48:26 +0000 | [diff] [blame] | 84 | except OSError: |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 85 | pass |
| 86 | try: |
| 87 | os.execvp(cmd[0], cmd) |
| 88 | finally: |
| 89 | os._exit(1) |
| 90 | |
Martin v. Löwis | 478c82d | 2006-03-24 08:14:54 +0000 | [diff] [blame] | 91 | def poll(self, _deadstate=None): |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 92 | """Return the exit status of the child process if it has finished, |
| 93 | or -1 if it hasn't finished yet.""" |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 94 | if self.sts < 0: |
| 95 | try: |
| 96 | pid, sts = os.waitpid(self.pid, os.WNOHANG) |
Martin v. Löwis | b95caff | 2006-03-24 08:26:26 +0000 | [diff] [blame] | 97 | # pid will be 0 if self.pid hasn't terminated |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 98 | if pid == self.pid: |
| 99 | self.sts = sts |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 100 | except os.error: |
Martin v. Löwis | 478c82d | 2006-03-24 08:14:54 +0000 | [diff] [blame] | 101 | if _deadstate is not None: |
| 102 | self.sts = _deadstate |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 103 | return self.sts |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 104 | |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 105 | def wait(self): |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 106 | """Wait for and return the exit status of the child process.""" |
Guido van Rossum | 3800ef7 | 2003-06-02 19:12:01 +0000 | [diff] [blame] | 107 | if self.sts < 0: |
| 108 | pid, sts = os.waitpid(self.pid, 0) |
Martin v. Löwis | b95caff | 2006-03-24 08:26:26 +0000 | [diff] [blame] | 109 | # This used to be a test, but it is believed to be |
| 110 | # always true, so I changed it to an assertion - mvl |
| 111 | assert pid == self.pid |
| 112 | self.sts = sts |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 113 | return self.sts |
Guido van Rossum | caa9f23 | 1997-04-21 14:15:55 +0000 | [diff] [blame] | 114 | |
Fred Drake | 31f182e | 2000-08-28 17:20:05 +0000 | [diff] [blame] | 115 | |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 116 | class Popen4(Popen3): |
| 117 | childerr = None |
| 118 | |
| 119 | def __init__(self, cmd, bufsize=-1): |
| 120 | _cleanup() |
Martin v. Löwis | 478c82d | 2006-03-24 08:14:54 +0000 | [diff] [blame] | 121 | self.cmd = cmd |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 122 | p2cread, p2cwrite = os.pipe() |
| 123 | c2pread, c2pwrite = os.pipe() |
| 124 | self.pid = os.fork() |
| 125 | if self.pid == 0: |
| 126 | # Child |
| 127 | os.dup2(p2cread, 0) |
| 128 | os.dup2(c2pwrite, 1) |
| 129 | os.dup2(c2pwrite, 2) |
| 130 | self._run_child(cmd) |
| 131 | os.close(p2cread) |
| 132 | self.tochild = os.fdopen(p2cwrite, 'w', bufsize) |
| 133 | os.close(c2pwrite) |
| 134 | self.fromchild = os.fdopen(c2pread, 'r', bufsize) |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 135 | |
| 136 | |
Andrew MacIntyre | 5cef571 | 2002-02-24 05:32:32 +0000 | [diff] [blame] | 137 | if sys.platform[:3] == "win" or sys.platform == "os2emx": |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 138 | # Some things don't make sense on non-Unix platforms. |
Tim Peters | d215218 | 2000-10-03 23:07:13 +0000 | [diff] [blame] | 139 | del Popen3, Popen4 |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 140 | |
| 141 | def popen2(cmd, bufsize=-1, mode='t'): |
Johannes Gijsbers | 9fc9789 | 2004-10-11 18:12:20 +0000 | [diff] [blame] | 142 | """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may |
| 143 | be a sequence, in which case arguments will be passed directly to the |
| 144 | program without shell intervention (as with os.spawnv()). If 'cmd' is a |
| 145 | string it will be passed to the shell (as with os.system()). If |
| 146 | 'bufsize' is specified, it sets the buffer size for the I/O pipes. The |
| 147 | file objects (child_stdout, child_stdin) are returned.""" |
Fredrik Lundh | 9ac81f6 | 2000-07-09 23:35:24 +0000 | [diff] [blame] | 148 | w, r = os.popen2(cmd, mode, bufsize) |
| 149 | return r, w |
Guido van Rossum | caa9f23 | 1997-04-21 14:15:55 +0000 | [diff] [blame] | 150 | |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 151 | def popen3(cmd, bufsize=-1, mode='t'): |
Johannes Gijsbers | 9fc9789 | 2004-10-11 18:12:20 +0000 | [diff] [blame] | 152 | """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may |
| 153 | be a sequence, in which case arguments will be passed directly to the |
| 154 | program without shell intervention (as with os.spawnv()). If 'cmd' is a |
| 155 | string it will be passed to the shell (as with os.system()). If |
| 156 | 'bufsize' is specified, it sets the buffer size for the I/O pipes. The |
| 157 | file objects (child_stdout, child_stdin, child_stderr) are returned.""" |
Fredrik Lundh | 9ac81f6 | 2000-07-09 23:35:24 +0000 | [diff] [blame] | 158 | w, r, e = os.popen3(cmd, mode, bufsize) |
| 159 | return r, w, e |
Fredrik Lundh | bb7eeff | 2000-07-09 17:59:32 +0000 | [diff] [blame] | 160 | |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 161 | def popen4(cmd, bufsize=-1, mode='t'): |
Johannes Gijsbers | 9fc9789 | 2004-10-11 18:12:20 +0000 | [diff] [blame] | 162 | """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may |
| 163 | be a sequence, in which case arguments will be passed directly to the |
| 164 | program without shell intervention (as with os.spawnv()). If 'cmd' is a |
| 165 | string it will be passed to the shell (as with os.system()). If |
| 166 | 'bufsize' is specified, it sets the buffer size for the I/O pipes. The |
| 167 | file objects (child_stdout_stderr, child_stdin) are returned.""" |
Fredrik Lundh | 9ac81f6 | 2000-07-09 23:35:24 +0000 | [diff] [blame] | 168 | w, r = os.popen4(cmd, mode, bufsize) |
| 169 | return r, w |
| 170 | else: |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 171 | def popen2(cmd, bufsize=-1, mode='t'): |
Johannes Gijsbers | 9fc9789 | 2004-10-11 18:12:20 +0000 | [diff] [blame] | 172 | """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may |
| 173 | be a sequence, in which case arguments will be passed directly to the |
| 174 | program without shell intervention (as with os.spawnv()). If 'cmd' is a |
| 175 | string it will be passed to the shell (as with os.system()). If |
| 176 | 'bufsize' is specified, it sets the buffer size for the I/O pipes. The |
| 177 | file objects (child_stdout, child_stdin) are returned.""" |
Fred Drake | b5aa407 | 2003-07-07 21:36:19 +0000 | [diff] [blame] | 178 | inst = Popen3(cmd, False, bufsize) |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 179 | return inst.fromchild, inst.tochild |
| 180 | |
| 181 | def popen3(cmd, bufsize=-1, mode='t'): |
Johannes Gijsbers | 9fc9789 | 2004-10-11 18:12:20 +0000 | [diff] [blame] | 182 | """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may |
| 183 | be a sequence, in which case arguments will be passed directly to the |
| 184 | program without shell intervention (as with os.spawnv()). If 'cmd' is a |
| 185 | string it will be passed to the shell (as with os.system()). If |
| 186 | 'bufsize' is specified, it sets the buffer size for the I/O pipes. The |
| 187 | file objects (child_stdout, child_stdin, child_stderr) are returned.""" |
Fred Drake | b5aa407 | 2003-07-07 21:36:19 +0000 | [diff] [blame] | 188 | inst = Popen3(cmd, True, bufsize) |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 189 | return inst.fromchild, inst.tochild, inst.childerr |
| 190 | |
| 191 | def popen4(cmd, bufsize=-1, mode='t'): |
Johannes Gijsbers | 9fc9789 | 2004-10-11 18:12:20 +0000 | [diff] [blame] | 192 | """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may |
| 193 | be a sequence, in which case arguments will be passed directly to the |
| 194 | program without shell intervention (as with os.spawnv()). If 'cmd' is a |
| 195 | string it will be passed to the shell (as with os.system()). If |
| 196 | 'bufsize' is specified, it sets the buffer size for the I/O pipes. The |
| 197 | file objects (child_stdout_stderr, child_stdin) are returned.""" |
Fred Drake | d75e63a | 2000-09-28 19:07:53 +0000 | [diff] [blame] | 198 | inst = Popen4(cmd, bufsize) |
| 199 | return inst.fromchild, inst.tochild |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 200 | |
Skip Montanaro | 352674d | 2001-02-07 23:14:30 +0000 | [diff] [blame] | 201 | __all__.extend(["Popen3", "Popen4"]) |
Tim Peters | 658cba6 | 2001-02-09 20:06:00 +0000 | [diff] [blame] | 202 | |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 203 | def _test(): |
Martin v. Löwis | bd8dbab | 2006-03-23 18:18:35 +0000 | [diff] [blame] | 204 | # When the test runs, there shouldn't be any open pipes |
| 205 | _cleanup() |
| 206 | assert not _active, "Active pipes when test starts " + repr([c.cmd for c in _active]) |
Tim Peters | 84f28db | 2000-08-20 05:57:36 +0000 | [diff] [blame] | 207 | cmd = "cat" |
Tim Peters | 3620857 | 2000-09-01 20:38:55 +0000 | [diff] [blame] | 208 | teststr = "ab cd\n" |
Tim Peters | 84f28db | 2000-08-20 05:57:36 +0000 | [diff] [blame] | 209 | if os.name == "nt": |
| 210 | cmd = "more" |
Tim Peters | 3620857 | 2000-09-01 20:38:55 +0000 | [diff] [blame] | 211 | # "more" doesn't act the same way across Windows flavors, |
| 212 | # sometimes adding an extra newline at the start or the |
| 213 | # end. So we strip whitespace off both ends for comparison. |
| 214 | expected = teststr.strip() |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 215 | print "testing popen2..." |
Tim Peters | 84f28db | 2000-08-20 05:57:36 +0000 | [diff] [blame] | 216 | r, w = popen2(cmd) |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 217 | w.write(teststr) |
| 218 | w.close() |
Tim Peters | 3620857 | 2000-09-01 20:38:55 +0000 | [diff] [blame] | 219 | got = r.read() |
| 220 | if got.strip() != expected: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 221 | raise ValueError("wrote %r read %r" % (teststr, got)) |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 222 | print "testing popen3..." |
Fredrik Lundh | bb7eeff | 2000-07-09 17:59:32 +0000 | [diff] [blame] | 223 | try: |
Tim Peters | 84f28db | 2000-08-20 05:57:36 +0000 | [diff] [blame] | 224 | r, w, e = popen3([cmd]) |
Fredrik Lundh | bb7eeff | 2000-07-09 17:59:32 +0000 | [diff] [blame] | 225 | except: |
Tim Peters | 84f28db | 2000-08-20 05:57:36 +0000 | [diff] [blame] | 226 | r, w, e = popen3(cmd) |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 227 | w.write(teststr) |
| 228 | w.close() |
Tim Peters | 3620857 | 2000-09-01 20:38:55 +0000 | [diff] [blame] | 229 | got = r.read() |
| 230 | if got.strip() != expected: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 231 | raise ValueError("wrote %r read %r" % (teststr, got)) |
Tim Peters | 3620857 | 2000-09-01 20:38:55 +0000 | [diff] [blame] | 232 | got = e.read() |
| 233 | if got: |
Andrew M. Kuchling | bfd7d6a | 2005-02-10 13:24:50 +0000 | [diff] [blame] | 234 | raise ValueError("unexpected %r on stderr" % (got,)) |
Guido van Rossum | 068d572 | 1999-04-20 12:27:31 +0000 | [diff] [blame] | 235 | for inst in _active[:]: |
| 236 | inst.wait() |
Martin v. Löwis | 478c82d | 2006-03-24 08:14:54 +0000 | [diff] [blame] | 237 | _cleanup() |
Tim Peters | 3620857 | 2000-09-01 20:38:55 +0000 | [diff] [blame] | 238 | if _active: |
| 239 | raise ValueError("_active not empty") |
Guido van Rossum | 0357d02 | 1997-08-11 03:27:24 +0000 | [diff] [blame] | 240 | print "All OK" |
| 241 | |
| 242 | if __name__ == '__main__': |
| 243 | _test() |