blob: cb769f886274833bda96938269648a0da742e5a5 [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
Neal Norwitz42dd86b2007-05-11 06:57:33 +000011import warnings
12warnings.warn("The popen2 module is deprecated. Use the subprocess module.",
13 DeprecationWarning, stacklevel=2)
Guido van Rossum9a22de11995-01-12 12:29:47 +000014
Skip Montanaro57fd45e2002-03-12 19:48:03 +000015__all__ = ["popen2", "popen3", "popen4"]
Skip Montanaro352674d2001-02-07 23:14:30 +000016
Martin v. Löwisf563c8b2003-10-06 21:34:33 +000017try:
18 MAXFD = os.sysconf('SC_OPEN_MAX')
19except (AttributeError, ValueError):
20 MAXFD = 256
Guido van Rossum9a22de11995-01-12 12:29:47 +000021
Guido van Rossum0357d021997-08-11 03:27:24 +000022_active = []
23
24def _cleanup():
25 for inst in _active[:]:
Martin v. Löwis478c82d2006-03-24 08:14:54 +000026 if inst.poll(_deadstate=sys.maxint) >= 0:
27 try:
28 _active.remove(inst)
29 except ValueError:
30 # This can happen if two threads create a new Popen instance.
31 # It's harmless that it was already removed, so ignore.
32 pass
Guido van Rossum0357d021997-08-11 03:27:24 +000033
34class Popen3:
Georg Brandlc45346f2008-01-06 14:33:52 +000035 """Class representing a child process. Normally, instances are created
36 internally by the functions popen2() and popen3()."""
Guido van Rossum54f22ed2000-02-04 15:10:34 +000037
Fred Draked75e63a2000-09-28 19:07:53 +000038 sts = -1 # Child not completed yet
39
Fred Drakeb5aa4072003-07-07 21:36:19 +000040 def __init__(self, cmd, capturestderr=False, bufsize=-1):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000041 """The parameter 'cmd' is the shell command to execute in a
Johannes Gijsbers9fc97892004-10-11 18:12:20 +000042 sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments
43 will be passed directly to the program without shell intervention (as
44 with os.spawnv()). If 'cmd' is a string it will be passed to the shell
45 (as with os.system()). The 'capturestderr' flag, if true, specifies
46 that the object should capture standard error output of the child
47 process. The default is false. If the 'bufsize' parameter is
48 specified, it specifies the size of the I/O buffers to/from the child
49 process."""
Fred Draked75e63a2000-09-28 19:07:53 +000050 _cleanup()
Martin v. Löwisbd8dbab2006-03-23 18:18:35 +000051 self.cmd = cmd
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000052 p2cread, p2cwrite = os.pipe()
53 c2pread, c2pwrite = os.pipe()
54 if capturestderr:
55 errout, errin = os.pipe()
56 self.pid = os.fork()
57 if self.pid == 0:
58 # Child
Fred Draked75e63a2000-09-28 19:07:53 +000059 os.dup2(p2cread, 0)
60 os.dup2(c2pwrite, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000061 if capturestderr:
Fred Draked75e63a2000-09-28 19:07:53 +000062 os.dup2(errin, 2)
63 self._run_child(cmd)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000064 os.close(p2cread)
65 self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
66 os.close(c2pwrite)
67 self.fromchild = os.fdopen(c2pread, 'r', bufsize)
68 if capturestderr:
69 os.close(errin)
70 self.childerr = os.fdopen(errout, 'r', bufsize)
71 else:
72 self.childerr = None
Martin v. Löwis478c82d2006-03-24 08:14:54 +000073
74 def __del__(self):
75 # In case the child hasn't been waited on, check if it's done.
76 self.poll(_deadstate=sys.maxint)
77 if self.sts < 0:
Georg Brandl4085f142006-07-21 17:36:31 +000078 if _active is not None:
Georg Brandlcfecd592006-05-25 18:44:09 +000079 # Child is still running, keep us alive until we can wait on it.
80 _active.append(self)
Guido van Rossum54f22ed2000-02-04 15:10:34 +000081
Fred Draked75e63a2000-09-28 19:07:53 +000082 def _run_child(self, cmd):
Walter Dörwald65230a22002-06-03 15:58:32 +000083 if isinstance(cmd, basestring):
Fred Draked75e63a2000-09-28 19:07:53 +000084 cmd = ['/bin/sh', '-c', cmd]
Georg Brandl8d01bb22008-02-23 22:09:24 +000085 os.closerange(3, MAXFD)
Fred Draked75e63a2000-09-28 19:07:53 +000086 try:
87 os.execvp(cmd[0], cmd)
88 finally:
89 os._exit(1)
90
Martin v. Löwis478c82d2006-03-24 08:14:54 +000091 def poll(self, _deadstate=None):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000092 """Return the exit status of the child process if it has finished,
93 or -1 if it hasn't finished yet."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000094 if self.sts < 0:
95 try:
96 pid, sts = os.waitpid(self.pid, os.WNOHANG)
Martin v. Löwisb95caff2006-03-24 08:26:26 +000097 # pid will be 0 if self.pid hasn't terminated
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000098 if pid == self.pid:
99 self.sts = sts
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 except os.error:
Martin v. Löwis478c82d2006-03-24 08:14:54 +0000101 if _deadstate is not None:
102 self.sts = _deadstate
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000103 return self.sts
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000104
Guido van Rossum0357d021997-08-11 03:27:24 +0000105 def wait(self):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000106 """Wait for and return the exit status of the child process."""
Guido van Rossum3800ef72003-06-02 19:12:01 +0000107 if self.sts < 0:
108 pid, sts = os.waitpid(self.pid, 0)
Martin v. Löwisb95caff2006-03-24 08:26:26 +0000109 # 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 Rossum45e2fbc1998-03-26 21:13:24 +0000113 return self.sts
Guido van Rossumcaa9f231997-04-21 14:15:55 +0000114
Fred Drake31f182e2000-08-28 17:20:05 +0000115
Fred Draked75e63a2000-09-28 19:07:53 +0000116class Popen4(Popen3):
117 childerr = None
118
119 def __init__(self, cmd, bufsize=-1):
120 _cleanup()
Martin v. Löwis478c82d2006-03-24 08:14:54 +0000121 self.cmd = cmd
Fred Draked75e63a2000-09-28 19:07:53 +0000122 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 Draked75e63a2000-09-28 19:07:53 +0000135
136
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000137if sys.platform[:3] == "win" or sys.platform == "os2emx":
Fred Draked75e63a2000-09-28 19:07:53 +0000138 # Some things don't make sense on non-Unix platforms.
Tim Petersd2152182000-10-03 23:07:13 +0000139 del Popen3, Popen4
Fred Draked75e63a2000-09-28 19:07:53 +0000140
141 def popen2(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000142 """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 Lundh9ac81f62000-07-09 23:35:24 +0000148 w, r = os.popen2(cmd, mode, bufsize)
149 return r, w
Guido van Rossumcaa9f231997-04-21 14:15:55 +0000150
Fred Draked75e63a2000-09-28 19:07:53 +0000151 def popen3(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000152 """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 Lundh9ac81f62000-07-09 23:35:24 +0000158 w, r, e = os.popen3(cmd, mode, bufsize)
159 return r, w, e
Fredrik Lundhbb7eeff2000-07-09 17:59:32 +0000160
Fred Draked75e63a2000-09-28 19:07:53 +0000161 def popen4(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000162 """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 Lundh9ac81f62000-07-09 23:35:24 +0000168 w, r = os.popen4(cmd, mode, bufsize)
169 return r, w
170else:
Fred Draked75e63a2000-09-28 19:07:53 +0000171 def popen2(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000172 """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 Drakeb5aa4072003-07-07 21:36:19 +0000178 inst = Popen3(cmd, False, bufsize)
Fred Draked75e63a2000-09-28 19:07:53 +0000179 return inst.fromchild, inst.tochild
180
181 def popen3(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000182 """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 Drakeb5aa4072003-07-07 21:36:19 +0000188 inst = Popen3(cmd, True, bufsize)
Fred Draked75e63a2000-09-28 19:07:53 +0000189 return inst.fromchild, inst.tochild, inst.childerr
190
191 def popen4(cmd, bufsize=-1, mode='t'):
Johannes Gijsbers9fc97892004-10-11 18:12:20 +0000192 """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 Draked75e63a2000-09-28 19:07:53 +0000198 inst = Popen4(cmd, bufsize)
199 return inst.fromchild, inst.tochild
Guido van Rossum0357d021997-08-11 03:27:24 +0000200
Skip Montanaro352674d2001-02-07 23:14:30 +0000201 __all__.extend(["Popen3", "Popen4"])