]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | r"""File-like objects that read from or write to a string buffer.\r |
2 | \r | |
3 | This implements (nearly) all stdio methods.\r | |
4 | \r | |
5 | f = StringIO() # ready for writing\r | |
6 | f = StringIO(buf) # ready for reading\r | |
7 | f.close() # explicitly release resources held\r | |
8 | flag = f.isatty() # always false\r | |
9 | pos = f.tell() # get current position\r | |
10 | f.seek(pos) # set current position\r | |
11 | f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF\r | |
12 | buf = f.read() # read until EOF\r | |
13 | buf = f.read(n) # read up to n bytes\r | |
14 | buf = f.readline() # read until end of line ('\n') or EOF\r | |
15 | list = f.readlines()# list of f.readline() results until EOF\r | |
16 | f.truncate([size]) # truncate file at to at most size (default: current pos)\r | |
17 | f.write(buf) # write at current position\r | |
18 | f.writelines(list) # for line in list: f.write(line)\r | |
19 | f.getvalue() # return whole file's contents as a string\r | |
20 | \r | |
21 | Notes:\r | |
22 | - Using a real file is often faster (but less convenient).\r | |
23 | - There's also a much faster implementation in C, called cStringIO, but\r | |
24 | it's not subclassable.\r | |
25 | - fileno() is left unimplemented so that code which uses it triggers\r | |
26 | an exception early.\r | |
27 | - Seeking far beyond EOF and then writing will insert real null\r | |
28 | bytes that occupy space in the buffer.\r | |
29 | - There's a simple test set (see end of this file).\r | |
30 | """\r | |
31 | try:\r | |
32 | from errno import EINVAL\r | |
33 | except ImportError:\r | |
34 | EINVAL = 22\r | |
35 | \r | |
36 | __all__ = ["StringIO"]\r | |
37 | \r | |
38 | def _complain_ifclosed(closed):\r | |
39 | if closed:\r | |
40 | raise ValueError, "I/O operation on closed file"\r | |
41 | \r | |
42 | class StringIO:\r | |
43 | """class StringIO([buffer])\r | |
44 | \r | |
45 | When a StringIO object is created, it can be initialized to an existing\r | |
46 | string by passing the string to the constructor. If no string is given,\r | |
47 | the StringIO will start empty.\r | |
48 | \r | |
49 | The StringIO object can accept either Unicode or 8-bit strings, but\r | |
50 | mixing the two may take some care. If both are used, 8-bit strings that\r | |
51 | cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause\r | |
52 | a UnicodeError to be raised when getvalue() is called.\r | |
53 | """\r | |
54 | def __init__(self, buf = ''):\r | |
55 | # Force self.buf to be a string or unicode\r | |
56 | if not isinstance(buf, basestring):\r | |
57 | buf = str(buf)\r | |
58 | self.buf = buf\r | |
59 | self.len = len(buf)\r | |
60 | self.buflist = []\r | |
61 | self.pos = 0\r | |
62 | self.closed = False\r | |
63 | self.softspace = 0\r | |
64 | \r | |
65 | def __iter__(self):\r | |
66 | return self\r | |
67 | \r | |
68 | def next(self):\r | |
69 | """A file object is its own iterator, for example iter(f) returns f\r | |
70 | (unless f is closed). When a file is used as an iterator, typically\r | |
71 | in a for loop (for example, for line in f: print line), the next()\r | |
72 | method is called repeatedly. This method returns the next input line,\r | |
73 | or raises StopIteration when EOF is hit.\r | |
74 | """\r | |
75 | _complain_ifclosed(self.closed)\r | |
76 | r = self.readline()\r | |
77 | if not r:\r | |
78 | raise StopIteration\r | |
79 | return r\r | |
80 | \r | |
81 | def close(self):\r | |
82 | """Free the memory buffer.\r | |
83 | """\r | |
84 | if not self.closed:\r | |
85 | self.closed = True\r | |
86 | del self.buf, self.pos\r | |
87 | \r | |
88 | def isatty(self):\r | |
89 | """Returns False because StringIO objects are not connected to a\r | |
90 | tty-like device.\r | |
91 | """\r | |
92 | _complain_ifclosed(self.closed)\r | |
93 | return False\r | |
94 | \r | |
95 | def seek(self, pos, mode = 0):\r | |
96 | """Set the file's current position.\r | |
97 | \r | |
98 | The mode argument is optional and defaults to 0 (absolute file\r | |
99 | positioning); other values are 1 (seek relative to the current\r | |
100 | position) and 2 (seek relative to the file's end).\r | |
101 | \r | |
102 | There is no return value.\r | |
103 | """\r | |
104 | _complain_ifclosed(self.closed)\r | |
105 | if self.buflist:\r | |
106 | self.buf += ''.join(self.buflist)\r | |
107 | self.buflist = []\r | |
108 | if mode == 1:\r | |
109 | pos += self.pos\r | |
110 | elif mode == 2:\r | |
111 | pos += self.len\r | |
112 | self.pos = max(0, pos)\r | |
113 | \r | |
114 | def tell(self):\r | |
115 | """Return the file's current position."""\r | |
116 | _complain_ifclosed(self.closed)\r | |
117 | return self.pos\r | |
118 | \r | |
119 | def read(self, n = -1):\r | |
120 | """Read at most size bytes from the file\r | |
121 | (less if the read hits EOF before obtaining size bytes).\r | |
122 | \r | |
123 | If the size argument is negative or omitted, read all data until EOF\r | |
124 | is reached. The bytes are returned as a string object. An empty\r | |
125 | string is returned when EOF is encountered immediately.\r | |
126 | """\r | |
127 | _complain_ifclosed(self.closed)\r | |
128 | if self.buflist:\r | |
129 | self.buf += ''.join(self.buflist)\r | |
130 | self.buflist = []\r | |
131 | if n is None or n < 0:\r | |
132 | newpos = self.len\r | |
133 | else:\r | |
134 | newpos = min(self.pos+n, self.len)\r | |
135 | r = self.buf[self.pos:newpos]\r | |
136 | self.pos = newpos\r | |
137 | return r\r | |
138 | \r | |
139 | def readline(self, length=None):\r | |
140 | r"""Read one entire line from the file.\r | |
141 | \r | |
142 | A trailing newline character is kept in the string (but may be absent\r | |
143 | when a file ends with an incomplete line). If the size argument is\r | |
144 | present and non-negative, it is a maximum byte count (including the\r | |
145 | trailing newline) and an incomplete line may be returned.\r | |
146 | \r | |
147 | An empty string is returned only when EOF is encountered immediately.\r | |
148 | \r | |
149 | Note: Unlike stdio's fgets(), the returned string contains null\r | |
150 | characters ('\0') if they occurred in the input.\r | |
151 | """\r | |
152 | _complain_ifclosed(self.closed)\r | |
153 | if self.buflist:\r | |
154 | self.buf += ''.join(self.buflist)\r | |
155 | self.buflist = []\r | |
156 | i = self.buf.find('\n', self.pos)\r | |
157 | if i < 0:\r | |
158 | newpos = self.len\r | |
159 | else:\r | |
160 | newpos = i+1\r | |
161 | if length is not None and length > 0:\r | |
162 | if self.pos + length < newpos:\r | |
163 | newpos = self.pos + length\r | |
164 | r = self.buf[self.pos:newpos]\r | |
165 | self.pos = newpos\r | |
166 | return r\r | |
167 | \r | |
168 | def readlines(self, sizehint = 0):\r | |
169 | """Read until EOF using readline() and return a list containing the\r | |
170 | lines thus read.\r | |
171 | \r | |
172 | If the optional sizehint argument is present, instead of reading up\r | |
173 | to EOF, whole lines totalling approximately sizehint bytes (or more\r | |
174 | to accommodate a final whole line).\r | |
175 | """\r | |
176 | total = 0\r | |
177 | lines = []\r | |
178 | line = self.readline()\r | |
179 | while line:\r | |
180 | lines.append(line)\r | |
181 | total += len(line)\r | |
182 | if 0 < sizehint <= total:\r | |
183 | break\r | |
184 | line = self.readline()\r | |
185 | return lines\r | |
186 | \r | |
187 | def truncate(self, size=None):\r | |
188 | """Truncate the file's size.\r | |
189 | \r | |
190 | If the optional size argument is present, the file is truncated to\r | |
191 | (at most) that size. The size defaults to the current position.\r | |
192 | The current file position is not changed unless the position\r | |
193 | is beyond the new file size.\r | |
194 | \r | |
195 | If the specified size exceeds the file's current size, the\r | |
196 | file remains unchanged.\r | |
197 | """\r | |
198 | _complain_ifclosed(self.closed)\r | |
199 | if size is None:\r | |
200 | size = self.pos\r | |
201 | elif size < 0:\r | |
202 | raise IOError(EINVAL, "Negative size not allowed")\r | |
203 | elif size < self.pos:\r | |
204 | self.pos = size\r | |
205 | self.buf = self.getvalue()[:size]\r | |
206 | self.len = size\r | |
207 | \r | |
208 | def write(self, s):\r | |
209 | """Write a string to the file.\r | |
210 | \r | |
211 | There is no return value.\r | |
212 | """\r | |
213 | _complain_ifclosed(self.closed)\r | |
214 | if not s: return\r | |
215 | # Force s to be a string or unicode\r | |
216 | if not isinstance(s, basestring):\r | |
217 | s = str(s)\r | |
218 | spos = self.pos\r | |
219 | slen = self.len\r | |
220 | if spos == slen:\r | |
221 | self.buflist.append(s)\r | |
222 | self.len = self.pos = spos + len(s)\r | |
223 | return\r | |
224 | if spos > slen:\r | |
225 | self.buflist.append('\0'*(spos - slen))\r | |
226 | slen = spos\r | |
227 | newpos = spos + len(s)\r | |
228 | if spos < slen:\r | |
229 | if self.buflist:\r | |
230 | self.buf += ''.join(self.buflist)\r | |
231 | self.buflist = [self.buf[:spos], s, self.buf[newpos:]]\r | |
232 | self.buf = ''\r | |
233 | if newpos > slen:\r | |
234 | slen = newpos\r | |
235 | else:\r | |
236 | self.buflist.append(s)\r | |
237 | slen = newpos\r | |
238 | self.len = slen\r | |
239 | self.pos = newpos\r | |
240 | \r | |
241 | def writelines(self, iterable):\r | |
242 | """Write a sequence of strings to the file. The sequence can be any\r | |
243 | iterable object producing strings, typically a list of strings. There\r | |
244 | is no return value.\r | |
245 | \r | |
246 | (The name is intended to match readlines(); writelines() does not add\r | |
247 | line separators.)\r | |
248 | """\r | |
249 | write = self.write\r | |
250 | for line in iterable:\r | |
251 | write(line)\r | |
252 | \r | |
253 | def flush(self):\r | |
254 | """Flush the internal buffer\r | |
255 | """\r | |
256 | _complain_ifclosed(self.closed)\r | |
257 | \r | |
258 | def getvalue(self):\r | |
259 | """\r | |
260 | Retrieve the entire contents of the "file" at any time before\r | |
261 | the StringIO object's close() method is called.\r | |
262 | \r | |
263 | The StringIO object can accept either Unicode or 8-bit strings,\r | |
264 | but mixing the two may take some care. If both are used, 8-bit\r | |
265 | strings that cannot be interpreted as 7-bit ASCII (that use the\r | |
266 | 8th bit) will cause a UnicodeError to be raised when getvalue()\r | |
267 | is called.\r | |
268 | """\r | |
269 | _complain_ifclosed(self.closed)\r | |
270 | if self.buflist:\r | |
271 | self.buf += ''.join(self.buflist)\r | |
272 | self.buflist = []\r | |
273 | return self.buf\r | |
274 | \r | |
275 | \r | |
276 | # A little test suite\r | |
277 | \r | |
278 | def test():\r | |
279 | import sys\r | |
280 | if sys.argv[1:]:\r | |
281 | file = sys.argv[1]\r | |
282 | else:\r | |
283 | file = '/etc/passwd'\r | |
284 | lines = open(file, 'r').readlines()\r | |
285 | text = open(file, 'r').read()\r | |
286 | f = StringIO()\r | |
287 | for line in lines[:-2]:\r | |
288 | f.write(line)\r | |
289 | f.writelines(lines[-2:])\r | |
290 | if f.getvalue() != text:\r | |
291 | raise RuntimeError, 'write failed'\r | |
292 | length = f.tell()\r | |
293 | print 'File length =', length\r | |
294 | f.seek(len(lines[0]))\r | |
295 | f.write(lines[1])\r | |
296 | f.seek(0)\r | |
297 | print 'First line =', repr(f.readline())\r | |
298 | print 'Position =', f.tell()\r | |
299 | line = f.readline()\r | |
300 | print 'Second line =', repr(line)\r | |
301 | f.seek(-len(line), 1)\r | |
302 | line2 = f.read(len(line))\r | |
303 | if line != line2:\r | |
304 | raise RuntimeError, 'bad result after seek back'\r | |
305 | f.seek(len(line2), 1)\r | |
306 | list = f.readlines()\r | |
307 | line = list[-1]\r | |
308 | f.seek(f.tell() - len(line))\r | |
309 | line2 = f.read()\r | |
310 | if line != line2:\r | |
311 | raise RuntimeError, 'bad result after seek back from EOF'\r | |
312 | print 'Read', len(list), 'more lines'\r | |
313 | print 'File length =', f.tell()\r | |
314 | if f.tell() != length:\r | |
315 | raise RuntimeError, 'bad length'\r | |
316 | f.truncate(length/2)\r | |
317 | f.seek(0, 2)\r | |
318 | print 'Truncated length =', f.tell()\r | |
319 | if f.tell() != length/2:\r | |
320 | raise RuntimeError, 'truncate did not adjust length'\r | |
321 | f.close()\r | |
322 | \r | |
323 | if __name__ == '__main__':\r | |
324 | test()\r |