1#!/usr/bin/env python 2 3# Copyright (c) Twisted Matrix Laboratories. 4# See LICENSE for details. 5 6 7import re 8 9from twisted.internet import protocol, reactor 10 11 12class MyPP(protocol.ProcessProtocol): 13 def __init__(self, verses): 14 self.verses = verses 15 self.data = "" 16 17 def connectionMade(self): 18 print("connectionMade!") 19 for i in range(self.verses): 20 self.transport.write( 21 "Aleph-null bottles of beer on the wall,\n" 22 + "Aleph-null bottles of beer,\n" 23 + "Take one down and pass it around,\n" 24 + "Aleph-null bottles of beer on the wall.\n" 25 ) 26 self.transport.closeStdin() # tell them we're done 27 28 def outReceived(self, data): 29 print("outReceived! with %d bytes!" % len(data)) 30 self.data = self.data + data 31 32 def errReceived(self, data): 33 print("errReceived! with %d bytes!" % len(data)) 34 35 def inConnectionLost(self): 36 print("inConnectionLost! stdin is closed! (we probably did it)") 37 38 def outConnectionLost(self): 39 print("outConnectionLost! The child closed their stdout!") 40 # now is the time to examine what they wrote 41 # print("I saw them write:", self.data) 42 (dummy, lines, words, chars, file) = re.split(r"\s+", self.data) 43 print("I saw %s lines" % lines) 44 45 def errConnectionLost(self): 46 print("errConnectionLost! The child closed their stderr.") 47 48 def processExited(self, reason): 49 print("processExited, status %d" % (reason.value.exitCode,)) 50 51 def processEnded(self, reason): 52 print("processEnded, status %d" % (reason.value.exitCode,)) 53 print("quitting") 54 reactor.stop() 55 56 57pp = MyPP(10) 58reactor.spawnProcess(pp, "wc", ["wc"], {}) 59reactor.run() 60