1. main.py:
1 #!/bin/env python
2 #-*-coding:utf-8-*-
3
4 import sys
5 from twisted.python import log
6 log.startLogging(sys.stdout)
7
8 from twisted.internet import protocol, reactor
9
10 class SubProcessProtocol(protocol.ProcessProtocol):
11 def __init__(self):
12 self.input = 97
13
14 def connectionMade(self):
15 log.msg('Connection Made.')
16 self.send()
17
18 def send(self):
19 self.transport.write(chr(self.input) + "\n")
20 log.msg('Sent:', chr(self.input))
21 self.input += 1
22
23 def outReceived(self, data):
24 log.msg('Received:', data)
25 reactor.callLater(.1, self.send)
26
27 def errReceived(self, data):
28 log.msg('Error:', data)
29
30 def inConnectionLost(self):
31 log.msg('Error: inConnectionLost')
32
33 def outConnectionLost(self):
34 log.msg('Error: inConnectionLost')
35
36 def errConnectionLost(self):
37 log.msg('Error: errConnectionLost')
38
39 def processExited(self, reason):
40 log.msg('Process exit status:',reason.value.exitCode )
41
42 def processEnded(self, reason):
43 log.msg('Process end status:',reason.value.exitCode )
44 if reactor.running:
45 reactor.stop()
46
47 def main():
48 p = SubProcessProtocol()
49 reactor.spawnProcess(p, 'sub.py', ['sub.py'], {})
50 reactor.run()
51
52 if __name__ == "__main__":
53 main()
2. sub.py:
1 #!/bin/env python
2 #-*-coding:utf-8-*-
3
4 import sys, os
5 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)
6
7
8 def main():
9 running = True
10
11 while running:
12 input = sys.stdin.readline().rstrip('\n')
13 if input == 'q':
14 running = False
15
16 print "You said:%s" % input
17
18 if __name__ == "__main__":
19 main()
20 sys.exit(2)