blob: bbd942854139b97fd3c5245ea22790ac927d8caa [file] [log] [blame]
Guido van Rossum85d89451994-06-23 11:53:27 +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
Guido van Rossumd3901021996-06-19 14:54:19 +000034 self.len = len(buf)
35 self.buflist = []
Guido van Rossum85d89451994-06-23 11:53:27 +000036 self.pos = 0
37 self.closed = 0
Guido van Rossum0daa13b1995-06-22 18:45:04 +000038 self.softspace = 0
Guido van Rossum85d89451994-06-23 11:53:27 +000039 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):
Guido van Rossumd3901021996-06-19 14:54:19 +000046 if self.buflist:
47 self.buf = self.buf + string.joinfields(self.buflist, '')
48 self.buflist = []
Guido van Rossum85d89451994-06-23 11:53:27 +000049 if mode == 1:
50 pos = pos + self.pos
51 elif mode == 2:
Guido van Rossumd3901021996-06-19 14:54:19 +000052 pos = pos + self.len
Guido van Rossum85d89451994-06-23 11:53:27 +000053 self.pos = max(0, pos)
54 def tell(self):
55 return self.pos
Guido van Rossumf7476c51996-01-25 17:34:14 +000056 def read(self, n = -1):
Guido van Rossumd3901021996-06-19 14:54:19 +000057 if self.buflist:
58 self.buf = self.buf + string.joinfields(self.buflist, '')
59 self.buflist = []
Guido van Rossumf7476c51996-01-25 17:34:14 +000060 if n < 0:
Guido van Rossumd3901021996-06-19 14:54:19 +000061 newpos = self.len
Guido van Rossum85d89451994-06-23 11:53:27 +000062 else:
Guido van Rossumd3901021996-06-19 14:54:19 +000063 newpos = min(self.pos+n, self.len)
Guido van Rossum85d89451994-06-23 11:53:27 +000064 r = self.buf[self.pos:newpos]
65 self.pos = newpos
66 return r
67 def readline(self):
Guido van Rossumd3901021996-06-19 14:54:19 +000068 if self.buflist:
69 self.buf = self.buf + string.joinfields(self.buflist, '')
70 self.buflist = []
Guido van Rossum85d89451994-06-23 11:53:27 +000071 i = string.find(self.buf, '\n', self.pos)
72 if i < 0:
Guido van Rossumd3901021996-06-19 14:54:19 +000073 newpos = self.len
Guido van Rossum85d89451994-06-23 11:53:27 +000074 else:
75 newpos = i+1
76 r = self.buf[self.pos:newpos]
77 self.pos = newpos
78 return r
79 def readlines(self):
80 lines = []
81 line = self.readline()
82 while line:
83 lines.append(line)
84 line = self.readline()
85 return lines
86 def write(self, s):
87 if not s: return
Guido van Rossumd3901021996-06-19 14:54:19 +000088 if self.pos > self.len:
89 self.buflist.append('\0'*(self.pos - self.len))
90 self.len = self.pos
Guido van Rossum85d89451994-06-23 11:53:27 +000091 newpos = self.pos + len(s)
Guido van Rossumd3901021996-06-19 14:54:19 +000092 if self.pos < self.len:
93 if self.buflist:
94 self.buf = self.buf + string.joinfields(self.buflist, '')
95 self.buflist = []
96 self.buflist = [self.buf[:self.pos], s, self.buf[newpos:]]
97 self.buf = ''
98 else:
99 self.buflist.append(s)
100 self.len = newpos
Guido van Rossum85d89451994-06-23 11:53:27 +0000101 self.pos = newpos
102 def writelines(self, list):
103 self.write(string.joinfields(list, ''))
Sjoerd Mullenderaa3e1631995-07-19 11:21:21 +0000104 def flush(self):
105 pass
Guido van Rossum85d89451994-06-23 11:53:27 +0000106 def getvalue(self):
Guido van Rossumd3901021996-06-19 14:54:19 +0000107 if self.buflist:
108 self.buf = self.buf + string.joinfields(self.buflist, '')
109 self.buflist = []
Guido van Rossum85d89451994-06-23 11:53:27 +0000110 return self.buf
111
112
113# A little test suite
114
115def test():
116 import sys
117 if sys.argv[1:]:
118 file = sys.argv[1]
119 else:
120 file = '/etc/passwd'
121 lines = open(file, 'r').readlines()
122 text = open(file, 'r').read()
123 f = StringIO()
124 for line in lines[:-2]:
125 f.write(line)
126 f.writelines(lines[-2:])
127 if f.getvalue() != text:
128 raise RuntimeError, 'write failed'
129 length = f.tell()
130 print 'File length =', length
131 f.seek(len(lines[0]))
132 f.write(lines[1])
133 f.seek(0)
134 print 'First line =', `f.readline()`
135 here = f.tell()
136 line = f.readline()
137 print 'Second line =', `line`
138 f.seek(-len(line), 1)
139 line2 = f.read(len(line))
140 if line != line2:
141 raise RuntimeError, 'bad result after seek back'
142 f.seek(len(line2), 1)
143 list = f.readlines()
144 line = list[-1]
145 f.seek(f.tell() - len(line))
146 line2 = f.read()
147 if line != line2:
148 raise RuntimeError, 'bad result after seek back from EOF'
149 print 'Read', len(list), 'more lines'
150 print 'File length =', f.tell()
151 if f.tell() != length:
152 raise RuntimeError, 'bad length'
153 f.close()
154
155if __name__ == '__main__':
156 test()