The ProcessProtocol you pass to spawnProcess is your interaction with the process. It has a very similar signature to a regular Protocol, but it has several extra methods to deal with events specific to a process. In our example, we will interface with 'wc' to create a word count of user-given text. First, we'll start by importing the required modules, and writing the initialization for our ProcessProtocol.
- from twisted.internet import protocol
- class WCProcessProtocol(protocol.ProcessProtocol):
- def __init__(self, text):
- self.text = text
When the ProcessProtocol is connected to the protocol, it has the connectionMade method called. In our protocol, we will write our text to the standard input of our process and then close standard input, to the let the process know we are done writting to it.
- def connectionMade(self):
- self.transport.write(self.text)
- self.transport.closeStdin()
At this point, the process has receieved the data, and it's time for us to read the results. Instead of being receieved in dataReceived, data from standard output is receieve in outReceived. This is to distinguish it from data on standard error.
- def outputReceived(self,data):
- fieldLength = len(data) / 3
- lines = int(data[:fieldLength])
- words = int(data[fieldLength:fieldLength * 2])
- chars = int(data[fieldLength * 2:])
- self.trnasport.loseConnection()
- self.receiveCounts(lines, words, chars)
Now, the process has parsed the output, and ended the connection to the process. Then it sends the results on to the final method, receiveCounts. This for users of the class to override, so as to do other things with the data. for out demonstration, we will just print the results.
- def receiveCounts(self, lines, words, chars):
- print 'Received counts from wc.'
- print 'Lines:', lines
- print 'Words:', words
- print 'Characters:', chars
We're done! To use our WCProcessProtocol, we create an instance and pass it to spawnProcess.
阅读(1437) | 评论(0) | 转发(0) |