blob: dba38e42c0a06271720a79ff7d71cf75fa160480 [file] [log] [blame]
Guido van Rossum5c971671996-07-22 15:23:25 +00001# class StringIO implements file-like objects that read/write a
2# string buffer (a.k.a. "memory files").
3#
4# This implements (nearly) all stdio methods.
5#
6# f = StringIO() # ready for writing
7# f = StringIO(buf) # ready for reading
8# f.close() # explicitly release resources held
9# flag = f.isatty() # always false
10# pos = f.tell() # get current position
11# f.seek(pos) # set current position
12# f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
13# buf = f.read() # read until EOF
14# buf = f.read(n) # read up to n bytes
15# buf = f.readline() # read until end of line ('\n') or EOF
16# list = f.readlines()# list of f.readline() results until EOF
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).
23# - fileno() is left unimplemented so that code which uses it triggers
24# an exception early.
25# - Seeking far beyond EOF and then writing will insert real null
26# bytes that occupy space in the buffer.
27# - There's a simple test set (see end of this file).
28
29import string
30
31class StringIO:
32 def __init__(self, buf = ''):
33 self.buf = buf
34 self.len = len(buf)
35 self.buflist = []
36 self.pos = 0
37 self.closed = 0
38 self.softspace = 0
39 def close(self):
40 if not self.closed:
41 self.closed = 1
42 del self.buf, self.pos
43 def isatty(self):
44 return 0
45 def seek(self, pos, mode = 0):
46 if self.buflist:
47 self.buf = self.buf + string.joinfields(self.buflist, '')
48 self.buflist = []
49 if mode == 1:
50 pos = pos + self.pos
51 elif mode == 2:
52 pos = pos + self.len
53 self.pos = max(0, pos)
54 def tell(self):
55 return self.pos
56 def read(self, n = -1):
57 if self.buflist:
58 self.buf = self.buf + string.joinfields(self.buflist, '')
59 self.buflist = []
60 if n < 0:
61 newpos = self.len
62 else:
63 newpos = min(self.pos+n, self.len)
64 r = self.buf[self.pos:newpos]
65 self.pos = newpos
66 return r
Guido van Rossumff712aa1997-08-15 00:45:26 +000067 def readline(self, length=None):
Guido van Rossum5c971671996-07-22 15:23:25 +000068 if self.buflist:
69 self.buf = self.buf + string.joinfields(self.buflist, '')
70 self.buflist = []
71 i = string.find(self.buf, '\n', self.pos)
72 if i < 0:
73 newpos = self.len
74 else:
75 newpos = i+1
Guido van Rossumff712aa1997-08-15 00:45:26 +000076 if length is not None:
77 if self.pos + length < newpos:
78 newpos = self.pos + length
Guido van Rossum5c971671996-07-22 15:23:25 +000079 r = self.buf[self.pos:newpos]
80 self.pos = newpos
81 return r
82 def readlines(self):
83 lines = []
84 line = self.readline()
85 while line:
86 lines.append(line)
87 line = self.readline()
88 return lines
89 def write(self, s):
90 if not s: return
91 if self.pos > self.len:
92 self.buflist.append('\0'*(self.pos - self.len))
93 self.len = self.pos
94 newpos = self.pos + len(s)
95 if self.pos < self.len:
96 if self.buflist:
97 self.buf = self.buf + string.joinfields(self.buflist, '')
98 self.buflist = []
99 self.buflist = [self.buf[:self.pos], s, self.buf[newpos:]]
100 self.buf = ''
101 else:
102 self.buflist.append(s)
103 self.len = newpos
104 self.pos = newpos
105 def writelines(self, list):
106 self.write(string.joinfields(list, ''))
107 def flush(self):
108 pass
109 def getvalue(self):
110 if self.buflist:
111 self.buf = self.buf + string.joinfields(self.buflist, '')
112 self.buflist = []
113 return self.buf
114
115
116# A little test suite
117
118def test():
119 import sys
120 if sys.argv[1:]:
121 file = sys.argv[1]
122 else:
123 file = '/etc/passwd'
124 lines = open(file, 'r').readlines()
125 text = open(file, 'r').read()
126 f = StringIO()
127 for line in lines[:-2]:
128 f.write(line)
129 f.writelines(lines[-2:])
130 if f.getvalue() != text:
131 raise RuntimeError, 'write failed'
132 length = f.tell()
133 print 'File length =', length
134 f.seek(len(lines[0]))
135 f.write(lines[1])
136 f.seek(0)
137 print 'First line =', `f.readline()`
138 here = f.tell()
139 line = f.readline()
140 print 'Second line =', `line`
141 f.seek(-len(line), 1)
142 line2 = f.read(len(line))
143 if line != line2:
144 raise RuntimeError, 'bad result after seek back'
145 f.seek(len(line2), 1)
146 list = f.readlines()
147 line = list[-1]
148 f.seek(f.tell() - len(line))
149 line2 = f.read()
150 if line != line2:
151 raise RuntimeError, 'bad result after seek back from EOF'
152 print 'Read', len(list), 'more lines'
153 print 'File length =', f.tell()
154 if f.tell() != length:
155 raise RuntimeError, 'bad length'
156 f.close()
157
158if __name__ == '__main__':
159 test()