blob: 694979e6d632a16cb598bf267cd8ada1e2bef41d [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""Spawn a command with pipes to its stdin, stdout, and optionally stderr.
2
3The normal os.popen(cmd, mode) call spawns a shell command and provides a
4file interface to just the input or output of the process depending on
5whether mode is 'r' or 'w'. This module provides the functions popen2(cmd)
6and popen3(cmd) which return two or three pipes to the spawned command.
7"""
8
Guido van Rossum9a22de11995-01-12 12:29:47 +00009import os
10import sys
Guido van Rossum9a22de11995-01-12 12:29:47 +000011
Skip Montanaro57fd45e2002-03-12 19:48:03 +000012__all__ = ["popen2", "popen3", "popen4"]
Skip Montanaro352674d2001-02-07 23:14:30 +000013
Martin v. Löwisf563c8b2003-10-06 21:34:33 +000014try:
15 MAXFD = os.sysconf('SC_OPEN_MAX')
16except (AttributeError, ValueError):
17 MAXFD = 256
Guido van Rossum9a22de11995-01-12 12:29:47 +000018
Guido van Rossum0357d021997-08-11 03:27:24 +000019_active = []
20
21def _cleanup():
22 for inst in _active[:]:
Martin v. Löwis478c82d2006-03-24 08:14:54 +000023 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 Rossum0357d021997-08-11 03:27:24 +000030
31class Popen3:
Guido van Rossum54f22ed2000-02-04 15:10:34 +000032 """Class representing a child process. Normally instances are created
33 by the factory functions popen2() and popen3()."""
34
Fred Draked75e63a2000-09-28 19:07:53 +000035 sts = -1 # Child not completed yet
36
Fred Drakeb5aa4072003-07-07 21:36:19 +000037 def __init__(self, cmd, capturestderr=False, bufsize=-1):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000038 """The parameter 'cmd' is the shell command to execute in a
Johannes Gijsbers9fc97892004-10-11 18:12:20 +000039 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 Draked75e63a2000-09-28 19:07:53 +000047 _cleanup()
Martin v. Löwisbd8dbab2006-03-23 18:18:35 +000048 self.cmd = cmd
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000049 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 Draked75e63a2000-09-28 19:07:53 +000056 os.dup2(p2cread, 0)
57 os.dup2(c2pwrite, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000058 if capturestderr:
Fred Draked75e63a2000-09-28 19:07:53 +000059 os.dup2(errin, 2)
60 self._run_child(cmd)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000061 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öwis478c82d2006-03-24 08:14:54 +000070
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:
Georg Brandl4085f142006-07-21 17:36:31 +000075 if _active is not None:
Georg Brandlcfecd592006-05-25 18:44:09 +000076 # Child is still running, keep us alive until we can wait on it.
77 _active.append(self)
Guido van Rossum54f22ed2000-02-04 15:10:34 +000078
Fred Draked75e63a2000-09-28 19:07:53 +000079 def _run_child(self, cmd):
Walter Dörwald65230a22002-06-03 15:58:32 +000080 if isinstance(cmd, basestring):
Fred Draked75e63a2000-09-28 19:07:53 +000081 cmd = ['/bin/sh', '-c', cmd]
Peter Astrandff355f12006-06-22 20:21:26 +000082 for i in xrange(3, MAXFD):
Fred Draked75e63a2000-09-28 19:07:53 +000083 try:
84 os.close(i)
Skip Montanaro1c90d7a2002-03-24 20:48:26 +000085 except OSError:
Fred Draked75e63a2000-09-28 19:07:53 +000086 pass
87 try:
88 os.execvp(cmd[0], cmd)
89 finally:
90 os._exit(1)
91
Martin v. Löwis478c82d2006-03-24 08:14:54 +000092 def poll(self, _deadstate=None):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000093 """Return the exit status of the child process if it has finished,
94 or -1 if it hasn't finished yet."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000095 if self.sts < 0:
96 try:
97 pid, sts = os.waitpid(self.pid, os.WNOHANG)
Martin v. Löwisb95caff2006-03-24 08:26:26 +000098 # pid will be 0 if self.pid hasn't terminated
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000099 if pid == self.pid:
100 self.sts = sts
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000101 except os.error:
Martin v. Löwis478c82d2006-03-24 08:14:54 +0000102 if _deadstate is not None:
103 self.sts = _deadstate
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000104 return self.sts
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000105
Guido van Rossum0357d021997-08-11 03:27:24 +0000106 def wait(self):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000107 """Wait for and return the exit status of the child process."""
Guido van Rossum3800ef72003-06-02 19:12:01 +0000108 if self.sts < 0:
109 pid, sts = os.waitpid(self.pid, 0)
Martin v. Löwisb95caff2006-03-24 08:26:26 +0000110 # This used to be a test, but it is believed to be
111 # always true, so I changed it to an assertion - mvl
112 assert pid == self.pid
113 self.sts = sts
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000114 return self.sts
Guido van Rossumcaa9f231997-04-21 14:15:55 +0000115
Fred Drake31f182e2000-08-28 17:20:05 +0000116
Fred Draked75e63a2000-09-28 19:07:53 +0000117class Popen4(Popen3):
118 childerr = None
119
120 def __init__(self, cmd, bufsize=-1):
121 _cleanup()
Martin v. Löwis478c82d2006-03-24 08:14:54 +0000122 self.cmd = cmd
Fred Draked75e63a2000-09-28 19:07:53 +0000123 p2cread, p2cwrite = os.pipe()
124 c2pread, c2pwrite = os.pipe()
125 self.pid = os.fork()
126 if self.pid == 0:
127 # Child
128 os.dup2(p2cread, 0)
129 os.dup2(c2pwrite, 1)
130 os.dup2(c2pwrite, 2)
131 self._run_child(cmd)
132 os.close(p2cread)
133 self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
134 os.close(c2pwrite)
135 self.fromchild = os.fdopen(c2pread, 'r', bufsize)
Fred Draked75e63a2000-09-28 19:07:53 +0000136
137
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000138if sys.platform[:3] == "win" or sys.platform == "os2emx":
Fred Draked75e63a2000-09-28 19:07:53 +0000139 # Some things don't make sense on non-Unix platforms.
Tim Petersd2152182000-10-03 23:07:13 +0000140 del Popen3, Popen4
Fred Draked75e63a2000-09-28 19:07:53 +0000141
142 def popen2(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000143 """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
144 be a sequence, in which case arguments will be passed directly to the
145 program without shell intervention (as with os.spawnv()). If 'cmd' is a
146 string it will be passed to the shell (as with os.system()). If
147 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
148 file objects (child_stdout, child_stdin) are returned."""
Fredrik Lundh9ac81f62000-07-09 23:35:24 +0000149 w, r = os.popen2(cmd, mode, bufsize)
150 return r, w
Guido van Rossumcaa9f231997-04-21 14:15:55 +0000151
Fred Draked75e63a2000-09-28 19:07:53 +0000152 def popen3(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000153 """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
154 be a sequence, in which case arguments will be passed directly to the
155 program without shell intervention (as with os.spawnv()). If 'cmd' is a
156 string it will be passed to the shell (as with os.system()). If
157 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
158 file objects (child_stdout, child_stdin, child_stderr) are returned."""
Fredrik Lundh9ac81f62000-07-09 23:35:24 +0000159 w, r, e = os.popen3(cmd, mode, bufsize)
160 return r, w, e
Fredrik Lundhbb7eeff2000-07-09 17:59:32 +0000161
Fred Draked75e63a2000-09-28 19:07:53 +0000162 def popen4(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000163 """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
164 be a sequence, in which case arguments will be passed directly to the
165 program without shell intervention (as with os.spawnv()). If 'cmd' is a
166 string it will be passed to the shell (as with os.system()). If
167 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
168 file objects (child_stdout_stderr, child_stdin) are returned."""
Fredrik Lundh9ac81f62000-07-09 23:35:24 +0000169 w, r = os.popen4(cmd, mode, bufsize)
170 return r, w
171else:
Fred Draked75e63a2000-09-28 19:07:53 +0000172 def popen2(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000173 """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
174 be a sequence, in which case arguments will be passed directly to the
175 program without shell intervention (as with os.spawnv()). If 'cmd' is a
176 string it will be passed to the shell (as with os.system()). If
177 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
178 file objects (child_stdout, child_stdin) are returned."""
Fred Drakeb5aa4072003-07-07 21:36:19 +0000179 inst = Popen3(cmd, False, bufsize)
Fred Draked75e63a2000-09-28 19:07:53 +0000180 return inst.fromchild, inst.tochild
181
182 def popen3(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000183 """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
184 be a sequence, in which case arguments will be passed directly to the
185 program without shell intervention (as with os.spawnv()). If 'cmd' is a
186 string it will be passed to the shell (as with os.system()). If
187 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
188 file objects (child_stdout, child_stdin, child_stderr) are returned."""
Fred Drakeb5aa4072003-07-07 21:36:19 +0000189 inst = Popen3(cmd, True, bufsize)
Fred Draked75e63a2000-09-28 19:07:53 +0000190 return inst.fromchild, inst.tochild, inst.childerr
191
192 def popen4(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000193 """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
194 be a sequence, in which case arguments will be passed directly to the
195 program without shell intervention (as with os.spawnv()). If 'cmd' is a
196 string it will be passed to the shell (as with os.system()). If
197 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
198 file objects (child_stdout_stderr, child_stdin) are returned."""
Fred Draked75e63a2000-09-28 19:07:53 +0000199 inst = Popen4(cmd, bufsize)
200 return inst.fromchild, inst.tochild
Guido van Rossum0357d021997-08-11 03:27:24 +0000201
Skip Montanaro352674d2001-02-07 23:14:30 +0000202 __all__.extend(["Popen3", "Popen4"])
Tim Peters658cba62001-02-09 20:06:00 +0000203
Guido van Rossum0357d021997-08-11 03:27:24 +0000204def _test():
Martin v. Löwisbd8dbab2006-03-23 18:18:35 +0000205 # When the test runs, there shouldn't be any open pipes
206 _cleanup()
207 assert not _active, "Active pipes when test starts " + repr([c.cmd for c in _active])
Tim Peters84f28db2000-08-20 05:57:36 +0000208 cmd = "cat"
Tim Peters36208572000-09-01 20:38:55 +0000209 teststr = "ab cd\n"
Tim Peters84f28db2000-08-20 05:57:36 +0000210 if os.name == "nt":
211 cmd = "more"
Tim Peters36208572000-09-01 20:38:55 +0000212 # "more" doesn't act the same way across Windows flavors,
213 # sometimes adding an extra newline at the start or the
214 # end. So we strip whitespace off both ends for comparison.
215 expected = teststr.strip()
Guido van Rossum0357d021997-08-11 03:27:24 +0000216 print "testing popen2..."
Tim Peters84f28db2000-08-20 05:57:36 +0000217 r, w = popen2(cmd)
Guido van Rossum0357d021997-08-11 03:27:24 +0000218 w.write(teststr)
219 w.close()
Tim Peters36208572000-09-01 20:38:55 +0000220 got = r.read()
221 if got.strip() != expected:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000222 raise ValueError("wrote %r read %r" % (teststr, got))
Guido van Rossum0357d021997-08-11 03:27:24 +0000223 print "testing popen3..."
Fredrik Lundhbb7eeff2000-07-09 17:59:32 +0000224 try:
Tim Peters84f28db2000-08-20 05:57:36 +0000225 r, w, e = popen3([cmd])
Fredrik Lundhbb7eeff2000-07-09 17:59:32 +0000226 except:
Tim Peters84f28db2000-08-20 05:57:36 +0000227 r, w, e = popen3(cmd)
Guido van Rossum0357d021997-08-11 03:27:24 +0000228 w.write(teststr)
229 w.close()
Tim Peters36208572000-09-01 20:38:55 +0000230 got = r.read()
231 if got.strip() != expected:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000232 raise ValueError("wrote %r read %r" % (teststr, got))
Tim Peters36208572000-09-01 20:38:55 +0000233 got = e.read()
234 if got:
Andrew M. Kuchlingbfd7d6a2005-02-10 13:24:50 +0000235 raise ValueError("unexpected %r on stderr" % (got,))
Guido van Rossum068d5721999-04-20 12:27:31 +0000236 for inst in _active[:]:
237 inst.wait()
Martin v. Löwis478c82d2006-03-24 08:14:54 +0000238 _cleanup()
Tim Peters36208572000-09-01 20:38:55 +0000239 if _active:
240 raise ValueError("_active not empty")
Guido van Rossum0357d021997-08-11 03:27:24 +0000241 print "All OK"
242
243if __name__ == '__main__':
244 _test()