SNIP IT: Popen3 in a non-heinous wrapper

Phlip phlip_cpp at yahoo.com
Thu May 2 12:33:46 EDT 2002


Not Hyp:

Despite the copious and well-consolidated documentation on the
subject, I have assembled a single, coherent wrapper for Popen3 that
hides the cluster of functions one must call to beat use out of it.
Find it below my sig.

Remember that the app it calls must call "flush" early and often; this
is an open issue.

Reviews & upgrades welcome.

--
  Phlip
               http://www.c2.com/cgi/wiki?PhlIp
  --  Argue for your <limits.h> and
      sure enough, they'r yours        --


import popen2
from fcntl import fcntl, F_SETFL
from select import select


def Piper(command, outputSink, errorSink):
	proc = popen2.Popen3(command, capturestderr = 1)
	O_NONBLOCK = 04000
	fcntl(proc.tochild.fileno(), F_SETFL, O_NONBLOCK)
	fcntl(proc.fromchild.fileno(), F_SETFL, O_NONBLOCK)
	fcntl(proc.childerr.fileno(), F_SETFL, O_NONBLOCK)

	while 1:
		w = []
		selectables = [proc.childerr, proc.fromchild]
		r, w, e = select(selectables, w, selectables)

		for i in r + e:
			if i == proc.childerr:
				err = proc.childerr.read()
				if err:  errorSink(err)

			if i == proc.fromchild:
				all = proc.fromchild.read()
				if all:  outputSink(all)

		got = proc.poll()
		if got != -1:
			break

	return got
			

if __name__ == '__main__':

	def outputSink(output):
		print output

	def errorSink(error):
		 print '***********************', error

	Piper(
		'ls . ; ls non_existent_folder ; ls .',
		outputSink,
		errorSink,
		)



More information about the Python-list mailing list