Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 1 | """File-like objects that read from or write to a string buffer. |
| 2 | |
| 3 | This implements (nearly) all stdio methods. |
| 4 | |
| 5 | f = StringIO() # ready for writing |
| 6 | f = StringIO(buf) # ready for reading |
| 7 | f.close() # explicitly release resources held |
| 8 | flag = f.isatty() # always false |
| 9 | pos = f.tell() # get current position |
| 10 | f.seek(pos) # set current position |
| 11 | f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF |
| 12 | buf = f.read() # read until EOF |
| 13 | buf = f.read(n) # read up to n bytes |
| 14 | buf = f.readline() # read until end of line ('\n') or EOF |
| 15 | list = f.readlines()# list of f.readline() results until EOF |
Fred Drake | e0a7f4f | 2000-09-28 04:21:06 +0000 | [diff] [blame] | 16 | f.truncate([size]) # truncate file at to at most size (default: current pos) |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 17 | f.write(buf) # write at current position |
| 18 | f.writelines(list) # for line in list: f.write(line) |
| 19 | f.getvalue() # return whole file's contents as a string |
| 20 | |
| 21 | Notes: |
| 22 | - Using a real file is often faster (but less convenient). |
Guido van Rossum | 98d9fd3 | 2000-02-28 15:12:25 +0000 | [diff] [blame] | 23 | - There's also a much faster implementation in C, called cStringIO, but |
| 24 | it's not subclassable. |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 25 | - fileno() is left unimplemented so that code which uses it triggers |
| 26 | an exception early. |
| 27 | - Seeking far beyond EOF and then writing will insert real null |
| 28 | bytes that occupy space in the buffer. |
| 29 | - There's a simple test set (see end of this file). |
| 30 | """ |
Barry Warsaw | c7ed0e3 | 2000-12-12 23:12:23 +0000 | [diff] [blame] | 31 | try: |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 32 | from errno import EINVAL |
Barry Warsaw | c7ed0e3 | 2000-12-12 23:12:23 +0000 | [diff] [blame] | 33 | except ImportError: |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 34 | EINVAL = 22 |
Barry Warsaw | c7ed0e3 | 2000-12-12 23:12:23 +0000 | [diff] [blame] | 35 | |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 36 | __all__ = ["StringIO"] |
| 37 | |
Guido van Rossum | 85d8945 | 1994-06-23 11:53:27 +0000 | [diff] [blame] | 38 | class StringIO: |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 39 | """class StringIO([buffer]) |
| 40 | |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 41 | When a StringIO object is created, it can be initialized to an existing |
| 42 | string by passing the string to the constructor. If no string is given, |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 43 | the StringIO will start empty. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 44 | |
| 45 | The StringIO object can accept either Unicode or 8-bit strings, but |
| 46 | mixing the two may take some care. If both are used, 8-bit strings that |
| 47 | cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 48 | a UnicodeError to be raised when getvalue() is called. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 49 | """ |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 50 | def __init__(self, buf = ''): |
Marc-André Lemburg | f853be9 | 2002-01-06 17:15:05 +0000 | [diff] [blame] | 51 | # Force self.buf to be a string or unicode |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 52 | if not isinstance(buf, basestring): |
Marc-André Lemburg | f853be9 | 2002-01-06 17:15:05 +0000 | [diff] [blame] | 53 | buf = str(buf) |
| 54 | self.buf = buf |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 55 | self.len = len(buf) |
| 56 | self.buflist = [] |
| 57 | self.pos = 0 |
| 58 | self.closed = 0 |
| 59 | self.softspace = 0 |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 60 | |
Barry Warsaw | bdefa0b | 2001-09-22 04:34:54 +0000 | [diff] [blame] | 61 | def __iter__(self): |
Guido van Rossum | c1265bd | 2003-01-31 16:04:15 +0000 | [diff] [blame] | 62 | return self |
| 63 | |
| 64 | def next(self): |
| 65 | if self.closed: |
| 66 | raise StopIteration |
| 67 | r = self.readline() |
| 68 | if not r: |
| 69 | raise StopIteration |
| 70 | return r |
Barry Warsaw | bdefa0b | 2001-09-22 04:34:54 +0000 | [diff] [blame] | 71 | |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 72 | def close(self): |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 73 | """Free the memory buffer. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 74 | """ |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 75 | if not self.closed: |
| 76 | self.closed = 1 |
| 77 | del self.buf, self.pos |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 78 | |
| 79 | def isatty(self): |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 80 | if self.closed: |
| 81 | raise ValueError, "I/O operation on closed file" |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 82 | return False |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 83 | |
| 84 | def seek(self, pos, mode = 0): |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 85 | if self.closed: |
| 86 | raise ValueError, "I/O operation on closed file" |
| 87 | if self.buflist: |
Marc-André Lemburg | 85d6edf | 2001-02-09 13:37:37 +0000 | [diff] [blame] | 88 | self.buf += ''.join(self.buflist) |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 89 | self.buflist = [] |
| 90 | if mode == 1: |
| 91 | pos += self.pos |
| 92 | elif mode == 2: |
| 93 | pos += self.len |
| 94 | self.pos = max(0, pos) |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 95 | |
| 96 | def tell(self): |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 97 | if self.closed: |
| 98 | raise ValueError, "I/O operation on closed file" |
| 99 | return self.pos |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 100 | |
| 101 | def read(self, n = -1): |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 102 | if self.closed: |
| 103 | raise ValueError, "I/O operation on closed file" |
| 104 | if self.buflist: |
Marc-André Lemburg | 85d6edf | 2001-02-09 13:37:37 +0000 | [diff] [blame] | 105 | self.buf += ''.join(self.buflist) |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 106 | self.buflist = [] |
| 107 | if n < 0: |
| 108 | newpos = self.len |
| 109 | else: |
| 110 | newpos = min(self.pos+n, self.len) |
| 111 | r = self.buf[self.pos:newpos] |
| 112 | self.pos = newpos |
| 113 | return r |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 114 | |
| 115 | def readline(self, length=None): |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 116 | if self.closed: |
| 117 | raise ValueError, "I/O operation on closed file" |
| 118 | if self.buflist: |
Marc-André Lemburg | 85d6edf | 2001-02-09 13:37:37 +0000 | [diff] [blame] | 119 | self.buf += ''.join(self.buflist) |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 120 | self.buflist = [] |
| 121 | i = self.buf.find('\n', self.pos) |
| 122 | if i < 0: |
| 123 | newpos = self.len |
| 124 | else: |
| 125 | newpos = i+1 |
| 126 | if length is not None: |
| 127 | if self.pos + length < newpos: |
| 128 | newpos = self.pos + length |
| 129 | r = self.buf[self.pos:newpos] |
| 130 | self.pos = newpos |
| 131 | return r |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 132 | |
| 133 | def readlines(self, sizehint = 0): |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 134 | total = 0 |
| 135 | lines = [] |
| 136 | line = self.readline() |
| 137 | while line: |
| 138 | lines.append(line) |
| 139 | total += len(line) |
| 140 | if 0 < sizehint <= total: |
| 141 | break |
| 142 | line = self.readline() |
| 143 | return lines |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 144 | |
| 145 | def truncate(self, size=None): |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 146 | if self.closed: |
| 147 | raise ValueError, "I/O operation on closed file" |
| 148 | if size is None: |
| 149 | size = self.pos |
| 150 | elif size < 0: |
| 151 | raise IOError(EINVAL, "Negative size not allowed") |
| 152 | elif size < self.pos: |
| 153 | self.pos = size |
| 154 | self.buf = self.getvalue()[:size] |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 155 | |
| 156 | def write(self, s): |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 157 | if self.closed: |
| 158 | raise ValueError, "I/O operation on closed file" |
| 159 | if not s: return |
Marc-André Lemburg | f853be9 | 2002-01-06 17:15:05 +0000 | [diff] [blame] | 160 | # Force s to be a string or unicode |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 161 | if not isinstance(s, basestring): |
Marc-André Lemburg | f853be9 | 2002-01-06 17:15:05 +0000 | [diff] [blame] | 162 | s = str(s) |
Fred Drake | d679e09 | 2002-09-17 18:10:34 +0000 | [diff] [blame] | 163 | if self.pos == self.len: |
| 164 | self.buflist.append(s) |
| 165 | self.len = self.pos = self.pos + len(s) |
| 166 | return |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 167 | if self.pos > self.len: |
| 168 | self.buflist.append('\0'*(self.pos - self.len)) |
| 169 | self.len = self.pos |
| 170 | newpos = self.pos + len(s) |
| 171 | if self.pos < self.len: |
| 172 | if self.buflist: |
Marc-André Lemburg | 85d6edf | 2001-02-09 13:37:37 +0000 | [diff] [blame] | 173 | self.buf += ''.join(self.buflist) |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 174 | self.buflist = [] |
| 175 | self.buflist = [self.buf[:self.pos], s, self.buf[newpos:]] |
| 176 | self.buf = '' |
| 177 | if newpos > self.len: |
| 178 | self.len = newpos |
| 179 | else: |
| 180 | self.buflist.append(s) |
| 181 | self.len = newpos |
| 182 | self.pos = newpos |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 183 | |
| 184 | def writelines(self, list): |
Marc-André Lemburg | 85d6edf | 2001-02-09 13:37:37 +0000 | [diff] [blame] | 185 | self.write(''.join(list)) |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 186 | |
| 187 | def flush(self): |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 188 | if self.closed: |
| 189 | raise ValueError, "I/O operation on closed file" |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 190 | |
| 191 | def getvalue(self): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 192 | """ |
| 193 | Retrieve the entire contents of the "file" at any time before |
| 194 | the StringIO object's close() method is called. |
| 195 | |
| 196 | The StringIO object can accept either Unicode or 8-bit strings, |
| 197 | but mixing the two may take some care. If both are used, 8-bit |
| 198 | strings that cannot be interpreted as 7-bit ASCII (that use the |
| 199 | 8th bit) will cause a UnicodeError to be raised when getvalue() |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 200 | is called. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 201 | """ |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 202 | if self.buflist: |
Marc-André Lemburg | 85d6edf | 2001-02-09 13:37:37 +0000 | [diff] [blame] | 203 | self.buf += ''.join(self.buflist) |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 204 | self.buflist = [] |
| 205 | return self.buf |
Guido van Rossum | 85d8945 | 1994-06-23 11:53:27 +0000 | [diff] [blame] | 206 | |
| 207 | |
| 208 | # A little test suite |
| 209 | |
| 210 | def test(): |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 211 | import sys |
| 212 | if sys.argv[1:]: |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 213 | file = sys.argv[1] |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 214 | else: |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 215 | file = '/etc/passwd' |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 216 | lines = open(file, 'r').readlines() |
| 217 | text = open(file, 'r').read() |
| 218 | f = StringIO() |
| 219 | for line in lines[:-2]: |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 220 | f.write(line) |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 221 | f.writelines(lines[-2:]) |
| 222 | if f.getvalue() != text: |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 223 | raise RuntimeError, 'write failed' |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 224 | length = f.tell() |
| 225 | print 'File length =', length |
| 226 | f.seek(len(lines[0])) |
| 227 | f.write(lines[1]) |
| 228 | f.seek(0) |
| 229 | print 'First line =', `f.readline()` |
Neal Norwitz | 9fb289d | 2002-02-11 17:52:18 +0000 | [diff] [blame] | 230 | print 'Position =', f.tell() |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 231 | line = f.readline() |
| 232 | print 'Second line =', `line` |
| 233 | f.seek(-len(line), 1) |
| 234 | line2 = f.read(len(line)) |
| 235 | if line != line2: |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 236 | raise RuntimeError, 'bad result after seek back' |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 237 | f.seek(len(line2), 1) |
| 238 | list = f.readlines() |
| 239 | line = list[-1] |
| 240 | f.seek(f.tell() - len(line)) |
| 241 | line2 = f.read() |
| 242 | if line != line2: |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 243 | raise RuntimeError, 'bad result after seek back from EOF' |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 244 | print 'Read', len(list), 'more lines' |
| 245 | print 'File length =', f.tell() |
| 246 | if f.tell() != length: |
Fred Drake | a63bd1c | 2000-12-13 20:23:11 +0000 | [diff] [blame] | 247 | raise RuntimeError, 'bad length' |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 248 | f.close() |
Guido van Rossum | 85d8945 | 1994-06-23 11:53:27 +0000 | [diff] [blame] | 249 | |
| 250 | if __name__ == '__main__': |
Barry Warsaw | c140131 | 2000-12-12 23:16:51 +0000 | [diff] [blame] | 251 | test() |