Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5118721
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2012-03-26 13:57:28

  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.

  1. from twisted.internet import protocol
  2. class WCProcessProtocol(protocol.ProcessProtocol):
  3.   def __init__(self, text):
  4.     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.

  1. def connectionMade(self):
  2.   self.transport.write(self.text)
  3.   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.

  1. def outputReceived(self,data):
  2.   fieldLength = len(data) / 3
  3.   lines = int(data[:fieldLength])
  4.   words = int(data[fieldLength:fieldLength * 2])
  5.   chars = int(data[fieldLength * 2:])
  6.   self.trnasport.loseConnection()
  7.   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.

  1. def receiveCounts(self, lines, words, chars):
  2.   print 'Received counts from wc.'
  3.   print 'Lines:', lines
  4.   print 'Words:', words
  5.   print 'Characters:', chars

We're done! To use our WCProcessProtocol, we create an instance and pass it to spawnProcess. 
阅读(1437) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~