1
2
3 '''
4 StreamCollector -- Runs as a thread and reads a single output stream of a process.
5
6 @author: Christian Holler (:decoder)
7
8 @license:
9
10 This Source Code Form is subject to the terms of the Mozilla Public
11 License, v. 2.0. If a copy of the MPL was not distributed with this
12 file, You can obtain one at http://mozilla.org/MPL/2.0/.
13
14 @contact: choller@mozilla.com
15 '''
16
17
18 from __future__ import print_function
19
20 import threading
21 from Queue import Queue
22
23
25 - def __init__(self, fd, responseQueue, logResponses = False, maxBacklog = None):
26 assert callable(fd.readline)
27 assert isinstance(responseQueue, Queue)
28
29 threading.Thread.__init__(self)
30
31 self.fd = fd
32 self.queue = responseQueue
33 self.output = []
34 self.responsePrefixes = []
35 self.logResponses = logResponses
36 self.maxBacklog = maxBacklog
37
39 while True:
40 line = self.fd.readline(4096)
41
42 if not line:
43 break
44
45 isResponse = False
46 for prefix in self.responsePrefixes:
47 if line.startswith(prefix):
48 self.queue.put(line.replace(prefix, '').rstrip('\n'))
49 isResponse = True
50 break
51
52 if not isResponse or self.logResponses:
53 self.output.append(line)
54
55
56 if self.maxBacklog != None and len(self.output) > self.maxBacklog:
57 self.output.pop(0)
58
59 self.fd.close()
60
62 self.responsePrefixes.append(prefix)
63