import os
import sys
import string

MAXFD = 100	# Max number of file descriptors (os.getdtablesize()???)

def popen2(cmd):
	cmd = ['/bin/sh', '-c', cmd]
	p2cread, p2cwrite = os.pipe()
	c2pread, c2pwrite = os.pipe()
	pid = os.fork()
	if pid == 0:
		# Child
		os.close(0)
		os.close(1)
		if os.dup(p2cread) <> 0:
			sys.stderr.write('popen2: bad read dup\n')
		if os.dup(c2pwrite) <> 1:
			sys.stderr.write('popen2: bad write dup\n')
		for i in range(3, MAXFD):
			try:
				os.close(i)
			except:
				pass
		try:
			os.execv(cmd[0], cmd)
		finally:
			os._exit(1)
		# Shouldn't come here, I guess
		os._exit(1)
	os.close(p2cread)
	tochild = os.fdopen(p2cwrite, 'w')
	os.close(c2pwrite)
	fromchild = os.fdopen(c2pread, 'r')
	return fromchild, tochild

@@ -103,16 +103,17 @@
 ?)%0A%0Adef 
+_
 popen2(c
@@ -114,16 +114,33 @@
 pen2(cmd
+, capturestderr=0
 ):%0A%09cmd 
@@ -226,16 +226,63 @@
 .pipe()%0A
+%09if capturestderr:%0A%09%09errout, errin = os.pipe()%0A
 %09pid = o
@@ -490,16 +490,82 @@
 dup%5Cn')%0A
+%09%09if capturestderr:%0A%09%09%09os.close(2)%0A%09%09%09if os.dup(errin) %3C%3E 2: pass%0A
 %09%09for i 
@@ -618,21 +618,17 @@
 %09except:
-%0A%09%09%09%09
+ 
 pass%0A%09%09t
@@ -846,30 +846,243 @@
 ')%0A%09
-return fromchild, tochild
+if capturestderr:%0A%09%09os.close(errin)%0A%09%09childerr = os.fdopen(errout, 'r')%0A%09%09return fromchild, tochild, childerr%0A%09else:%0A%09%09return fromchild, tochild, None%0A%0Adef popen2(cmd):%0A%09return _popen2(cmd, 0)%5B:2%5D%0A%0Adef popen3(cmd):%0A%09return _popen2(cmd, 1)
 %0A

Change inspired by Tommy Burnette to add an interface to get stderr, too.