chiark / gitweb /
Add asynchronous filereader, fix python3 lockups
[fdroidserver.git] / fdroidserver / asynchronousfilereader / __init__.py
1 """
2 AsynchronousFileReader
3 ======================
4
5 Simple thread based asynchronous file reader for Python.
6
7 see https://github.com/soxofaan/asynchronousfilereader
8
9 MIT License
10 Copyright (c) 2014 Stefaan Lippens
11 """
12
13 __version__ = '0.2.1'
14
15 import threading
16 try:
17     # Python 2
18     from Queue import Queue
19 except ImportError:
20     # Python 3
21     from queue import Queue
22
23
24 class AsynchronousFileReader(threading.Thread):
25     """
26     Helper class to implement asynchronous reading of a file
27     in a separate thread. Pushes read lines on a queue to
28     be consumed in another thread.
29     """
30
31     def __init__(self, fd, queue=None, autostart=True):
32         self._fd = fd
33         if queue is None:
34             queue = Queue()
35         self.queue = queue
36
37         threading.Thread.__init__(self)
38
39         if autostart:
40             self.start()
41
42     def run(self):
43         """
44         The body of the tread: read lines and put them on the queue.
45         """
46         while True:
47             line = self._fd.readline()
48             if not line:
49                 break
50             self.queue.put(line)
51
52     def eof(self):
53         """
54         Check whether there is no more content to expect.
55         """
56         return not self.is_alive() and self.queue.empty()
57
58     def readlines(self):
59         """
60         Get currently available lines.
61         """
62         while not self.queue.empty():
63             yield self.queue.get()
64