blob: cb7313d42a92c9de496eaef1a812b78be7a5d61f [file] [log] [blame]
Guido van Rossum4acc25b2000-02-02 15:10:15 +00001"""File-like objects that read from or write to a string buffer.
2
3This implements (nearly) all stdio methods.
4
5f = StringIO() # ready for writing
6f = StringIO(buf) # ready for reading
7f.close() # explicitly release resources held
8flag = f.isatty() # always false
9pos = f.tell() # get current position
10f.seek(pos) # set current position
11f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
12buf = f.read() # read until EOF
13buf = f.read(n) # read up to n bytes
14buf = f.readline() # read until end of line ('\n') or EOF
15list = f.readlines()# list of f.readline() results until EOF
Fred Drakee0a7f4f2000-09-28 04:21:06 +000016f.truncate([size]) # truncate file at to at most size (default: current pos)
Guido van Rossum4acc25b2000-02-02 15:10:15 +000017f.write(buf) # write at current position
18f.writelines(list) # for line in list: f.write(line)
19f.getvalue() # return whole file's contents as a string
20
21Notes:
22- Using a real file is often faster (but less convenient).
Guido van Rossum98d9fd32000-02-28 15:12:25 +000023- There's also a much faster implementation in C, called cStringIO, but
24 it's not subclassable.
Guido van Rossum4acc25b2000-02-02 15:10:15 +000025- 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"""
Guido van Rossum85d89451994-06-23 11:53:27 +000031
Barry Warsawc7ed0e32000-12-12 23:12:23 +000032try:
Barry Warsawc1401312000-12-12 23:16:51 +000033 from errno import EINVAL
Barry Warsawc7ed0e32000-12-12 23:12:23 +000034except ImportError:
Barry Warsawc1401312000-12-12 23:16:51 +000035 EINVAL = 22
Barry Warsawc7ed0e32000-12-12 23:12:23 +000036
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000037__all__ = ["StringIO"]
38
Guido van Rossum85d89451994-06-23 11:53:27 +000039class StringIO:
Barry Warsawc1401312000-12-12 23:16:51 +000040 def __init__(self, buf = ''):
Fred Drakea63bd1c2000-12-13 20:23:11 +000041 self.buf = buf
42 self.len = len(buf)
43 self.buflist = []
44 self.pos = 0
45 self.closed = 0
46 self.softspace = 0
Barry Warsawc1401312000-12-12 23:16:51 +000047
Barry Warsawbdefa0b2001-09-22 04:34:54 +000048 def __iter__(self):
49 return iter(self.readline, '')
50
Barry Warsawc1401312000-12-12 23:16:51 +000051 def close(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +000052 if not self.closed:
53 self.closed = 1
54 del self.buf, self.pos
Barry Warsawc1401312000-12-12 23:16:51 +000055
56 def isatty(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +000057 if self.closed:
58 raise ValueError, "I/O operation on closed file"
59 return 0
Barry Warsawc1401312000-12-12 23:16:51 +000060
61 def seek(self, pos, mode = 0):
Fred Drakea63bd1c2000-12-13 20:23:11 +000062 if self.closed:
63 raise ValueError, "I/O operation on closed file"
64 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +000065 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +000066 self.buflist = []
67 if mode == 1:
68 pos += self.pos
69 elif mode == 2:
70 pos += self.len
71 self.pos = max(0, pos)
Barry Warsawc1401312000-12-12 23:16:51 +000072
73 def tell(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +000074 if self.closed:
75 raise ValueError, "I/O operation on closed file"
76 return self.pos
Barry Warsawc1401312000-12-12 23:16:51 +000077
78 def read(self, n = -1):
Fred Drakea63bd1c2000-12-13 20:23:11 +000079 if self.closed:
80 raise ValueError, "I/O operation on closed file"
81 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +000082 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +000083 self.buflist = []
84 if n < 0:
85 newpos = self.len
86 else:
87 newpos = min(self.pos+n, self.len)
88 r = self.buf[self.pos:newpos]
89 self.pos = newpos
90 return r
Barry Warsawc1401312000-12-12 23:16:51 +000091
92 def readline(self, length=None):
Fred Drakea63bd1c2000-12-13 20:23:11 +000093 if self.closed:
94 raise ValueError, "I/O operation on closed file"
95 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +000096 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +000097 self.buflist = []
98 i = self.buf.find('\n', self.pos)
99 if i < 0:
100 newpos = self.len
101 else:
102 newpos = i+1
103 if length is not None:
104 if self.pos + length < newpos:
105 newpos = self.pos + length
106 r = self.buf[self.pos:newpos]
107 self.pos = newpos
108 return r
Barry Warsawc1401312000-12-12 23:16:51 +0000109
110 def readlines(self, sizehint = 0):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000111 total = 0
112 lines = []
113 line = self.readline()
114 while line:
115 lines.append(line)
116 total += len(line)
117 if 0 < sizehint <= total:
118 break
119 line = self.readline()
120 return lines
Barry Warsawc1401312000-12-12 23:16:51 +0000121
122 def truncate(self, size=None):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000123 if self.closed:
124 raise ValueError, "I/O operation on closed file"
125 if size is None:
126 size = self.pos
127 elif size < 0:
128 raise IOError(EINVAL, "Negative size not allowed")
129 elif size < self.pos:
130 self.pos = size
131 self.buf = self.getvalue()[:size]
Barry Warsawc1401312000-12-12 23:16:51 +0000132
133 def write(self, s):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000134 if self.closed:
135 raise ValueError, "I/O operation on closed file"
136 if not s: return
137 if self.pos > self.len:
138 self.buflist.append('\0'*(self.pos - self.len))
139 self.len = self.pos
140 newpos = self.pos + len(s)
141 if self.pos < self.len:
142 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +0000143 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +0000144 self.buflist = []
145 self.buflist = [self.buf[:self.pos], s, self.buf[newpos:]]
146 self.buf = ''
147 if newpos > self.len:
148 self.len = newpos
149 else:
150 self.buflist.append(s)
151 self.len = newpos
152 self.pos = newpos
Barry Warsawc1401312000-12-12 23:16:51 +0000153
154 def writelines(self, list):
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +0000155 self.write(''.join(list))
Barry Warsawc1401312000-12-12 23:16:51 +0000156
157 def flush(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000158 if self.closed:
159 raise ValueError, "I/O operation on closed file"
Barry Warsawc1401312000-12-12 23:16:51 +0000160
161 def getvalue(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000162 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +0000163 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +0000164 self.buflist = []
165 return self.buf
Guido van Rossum85d89451994-06-23 11:53:27 +0000166
167
168# A little test suite
169
170def test():
Barry Warsawc1401312000-12-12 23:16:51 +0000171 import sys
172 if sys.argv[1:]:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000173 file = sys.argv[1]
Barry Warsawc1401312000-12-12 23:16:51 +0000174 else:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000175 file = '/etc/passwd'
Barry Warsawc1401312000-12-12 23:16:51 +0000176 lines = open(file, 'r').readlines()
177 text = open(file, 'r').read()
178 f = StringIO()
179 for line in lines[:-2]:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000180 f.write(line)
Barry Warsawc1401312000-12-12 23:16:51 +0000181 f.writelines(lines[-2:])
182 if f.getvalue() != text:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000183 raise RuntimeError, 'write failed'
Barry Warsawc1401312000-12-12 23:16:51 +0000184 length = f.tell()
185 print 'File length =', length
186 f.seek(len(lines[0]))
187 f.write(lines[1])
188 f.seek(0)
189 print 'First line =', `f.readline()`
190 here = f.tell()
191 line = f.readline()
192 print 'Second line =', `line`
193 f.seek(-len(line), 1)
194 line2 = f.read(len(line))
195 if line != line2:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000196 raise RuntimeError, 'bad result after seek back'
Barry Warsawc1401312000-12-12 23:16:51 +0000197 f.seek(len(line2), 1)
198 list = f.readlines()
199 line = list[-1]
200 f.seek(f.tell() - len(line))
201 line2 = f.read()
202 if line != line2:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000203 raise RuntimeError, 'bad result after seek back from EOF'
Barry Warsawc1401312000-12-12 23:16:51 +0000204 print 'Read', len(list), 'more lines'
205 print 'File length =', f.tell()
206 if f.tell() != length:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000207 raise RuntimeError, 'bad length'
Barry Warsawc1401312000-12-12 23:16:51 +0000208 f.close()
Guido van Rossum85d89451994-06-23 11:53:27 +0000209
210if __name__ == '__main__':
Barry Warsawc1401312000-12-12 23:16:51 +0000211 test()